Reputation: 409
Can anyone explain the order in which below console logs are getting printed? I am using async version 1.4.23 .
response contains two items.
output: label 1
label 2
label 2
label 4
label 3
label 3
async.parallel([
function(callback){
detailsData.list({}, function(err, response) {
if (!err) {
console.log("label 1");
async.each(response, function(item, cb) {
console.log("label 2");
itemList.getData(item, function(err, response) {
console.log("label 3");
}
cb(err);
});
});
}
callback(err);
});
},
function (callback) {
somefunction();
}], function (err) {
console.log("label 4");
}
Why is label 3 not printed before label 4?
Upvotes: 1
Views: 1187
Reputation: 664196
You will have to pass the callback
that you get from async.parallel
to async.each
instead of invoking it immediately, otherwise the parallel execution won't wait for the each.
async.parallel([
function(callback){
detailsData.list({}, function(err, response) {
if (err) return callback(err); // <- still call it when you're not going for the each
console.log("label 1");
async.each(response, function(item, cb) {
console.log("label 2");
itemList.getData(item, function(err, response) {
console.log("label 3");
cb(err, response);
});
}, callback);
// ^^^^^^^^
});
},
function(callback) {
somefunction();
callback();
}
], function(err) {
console.log("label 4");
});
Upvotes: 1