1
有一个函数,它需要遍历数组,对每个项目执行异步操作,然后最终回调给调用者。Node.js使用async.forEach与异步操作
我可以得到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);
}
);
}
其中创建()是我的新异步操作。 现在我得到一个无限循环,我们似乎从来没有打回调(createdList);
我的事件试图在异步create()方法的回调中移动callback(),但这两者都不起作用。
请帮助我,我卡在回拨地狱!
在'create'回调中调用'callback()'是实现这一点的方法。不知道为什么这不适合你。 – JohnnyHK
也不确定。想知道是否因为回调被定义了两次。一次在循环中,再次在包含函数中。想知道它是否变得困惑。 –
btw。 async.forEach和async.each有什么区别? –