具有一个函数,该函数需要遍历数组,对每个项目执行异步操作,然后最终回调到调用方。
我可以得到async.forEach正常工作的基本情况。当我这样做时,它会起作用
async.forEach(documentDefinitions(), function (documentDefinition, callback) {
createdList.push(documentDefinition);
callback(); //tell the async iterator we're done
}, function (err) {
console.log('iterating done ' + createdList.length);
callback(createdList); //tell the calling method we're done, and return the created docs.
});
createdList的长度是正确的长度。
现在,我想每次通过循环执行另一个异步操作。因此,我尝试将代码更改为以下内容;
function insert(link, callback){
var createList = [];
async.each(
documentDefinitions(),
function iterator(item, callback) {
create(collectionLink, item, function (err, created) {
console.log('created');
createdList.push(created);
callback();
});
},
function (err) {
console.log('iterating done ' + createdList.length);
callback(createdList);
}
);
}
其中create()是我的新异步操作。现在我得到一个无休止的循环,我们似乎再也没有碰到callback(createdList);
我事件尝试将callback()移到异步create()方法的回调中,但是这些都不起作用。
请帮助我,我陷入了回调地狱!
将func更改为以下内容将其修复。
function insert(link, callback){
var createdList = [];
async.each(
documentDefinitions(),
function iterator(item, cb) {
create(collectionLink, item, function (err, created) {
console.log('created');
createdList.push(created);
cb();
});
},
function (err) {
console.log('iterating done ' + createdList.length);
callback(createdList);
}
);
}
不能确定,但是我认为这是将一次发生的回调更改为cb起到了作用。
这是一个范围界定的问题,他们开始感到困惑了吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句