我有三个操作要一个接一个地进行
1.从db
中获取一些行2. forloop中的另一个mysql查询,用于获取一些数据并存储在变量
中3.显示数据
我正在使用async
waterfall
方法。
async.waterfall([
function(callback){
//first sql and pass the result to second function
collection.getAllCollections(function (status,error,result) {
callback(null,result);
});
},
//running another query in loop with result with previous
function(result, callback){
for(var i=0;i<result.length;i++){
collection.getImages(result[i].id,function (status,error,user) {
//append the query result to old result
result[i]['users'] = user;
});
}
callback(null,result);
}
], function (err, result) {
console.log("result",result);
});
但问题final result
不包含user
结果,因为第二个查询(for循环中的查询是异步的)
答案 0 :(得分:1)
你意识到了手头的问题。你的回调基本上必须等待for循环结束。 例如:
async.waterfall([
function(next){
//first sql and pass the result to second function
collection.getAllCollections(function (status,error,result) {
next(null, result);
});
},
function(result, next){
var calls = [];
//putting every call in an array
result.forEach(function(resultObject){
calls.push(function(callback) {
collection.getImages(resultObject.id, function (status, error, user) {
resultObject['users'] = user;
callback(null, resultObject);
});
}
)});
//performing calls async parallel to each other
async.parallel(calls, function(err, results) {
//executed as soon as all calls are finished
if (err) {
next(err, null);
} else {
next(null, results);
}
});
}
], function (err, result) {
console.log("result",result);
});