Javascript 嵌套异步函数
使用下面的代码,我可以确保最后一次回调将返回更新的变量吗Javascript 嵌套异步函数,javascript,callback,async.js,Javascript,Callback,Async.js,使用下面的代码,我可以确保最后一次回调将返回更新的变量吗 var a = 0; async.forEach(collectionarray, function(item, cb1) { async.forEach(collection.anotherarray, function(item, cb2) { a += item.number; cb2(); }, function(err) { if(err) console.log(
var a = 0;
async.forEach(collectionarray, function(item, cb1) {
async.forEach(collection.anotherarray, function(item, cb2) {
a += item.number;
cb2();
}, function(err) {
if(err) console.log(err);
})
cb1();
}, function(err) {
if(err) console.log(err);
console.log(a); // will this be updated for all the collection.anotherarray.number ?
})
.forEach
的第三个参数有两个用途:当所有迭代完成时作为回调,或者报告错误。在内部上的回调中调用cb1()
。forEach
:
var a = 0;
async.forEach(collectionarray, function(item, cb1) {
async.forEach(collection.anotherarray, function(item, cb2) {
a += item.number;
cb2();
}, function(err) {
if(err) console.log(err);
cb1();
});
}, function(err) {
if(err) console.log(err);
console.log(a);
})
您所编写的方法几乎肯定无法正常工作。外部的
.forEach
会认为它做得太快了。您应该将cb1
作为回调传递到内部的forEach
,而不是立即调用它@Bergi你的意思是在内部异步的最终回调中调用它?