我试图从node.js 理解async
库并应用它,但它没有按预期工作。当我期望它们是系列制作(即一个接一个)时,调用是并行制作的
这是我的代码
var users = [{_id:'1',username:'user1'},{_id:'2',username:'user2'}];
async.eachSeries(users,function function1(user,callbackEach){
var username = user.username;
var incomes = [{source:'sourceA',provider:providerA},{source:'sourceB',provider:providerB},{source:'sourceC',provider:providerC}];
async.eachSeries(incomes,function function2(income,callbackSmallEach){
var source = income.source;
income.provider.getEarnings(user._id,username,yesterday,function callbackFromGetEarnings(err,result){
if (err){
// error
} else {
income.earnings = {day : new Number(result)};
income.provider.getMonthEarnings(user._id,username,yesterday,function callbackFromGetMonthEarnings(err,monthTotal){
if (err){
// error
} else {
income.earnings.month = new Number(monthTotal);
callbackSmallEach();
}
});
}
});
},
function sendEmails(err){
if (err) {
// error
} else {
// send email
}
});
console.log("Just before calling callbackEach()");
callbackEach();
});
getEarnings
和 getMonthEarnings
使用外部提供程序,因此在回调函数 callbackFromGetEarnings
和 callbackFromGetMonthEarnings
之前可能会发生一段时间被调用。
我的问题是,我不希望同时执行对 getEarnings
的两次调用。我希望仅在 user1
的 getEarnings
返回后调用 user2
的函数 getEarnings
(并且相应的回调已被调用)制成)。
正如您所看到的,我尝试使用 async.eachSeries
在系列中对 user1 和 2 进行调用,但调用是并行进行的。当我执行时,日志 Just before callcallbackEach()
始终在调用回调函数 callbackFromGetEarnings
之前执行...
我希望这已经足够清楚了。
最佳答案
问题在于您调用回调的位置。示例:
async.eachSeries(something, function(item, callback) {
async.eachSeries(item.somethingElse, function(subitem, callback2) {
//do something
return callback2();
}, function() {
//when all item.somethingElse is done, call the upper callback
return callback();
})
}, function() {
console.log('done');
})
这样,对于某项中的每个项目,您将在转到下一个项目之前依次执行所有 item.somethingElse。
关于javascript - Async.eachSeries 并行执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45085928/