Node.js使用async.forEach与异步操作

Node.js using async.forEach with async operation

本文关键字:异步操作 forEach async js 使用 Node      更新时间:2023-09-26

有一个函数,它需要遍历数组,对每一项执行异步操作,然后最后回调给调用者。

我可以得到async的基本情况。每个人都去工作。当我这样做的时候,它可以工作

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()是我新的异步操作。现在我得到一个无限循环,我们似乎从来没有点击回调(createdList);

我尝试将callback()移动到async create()方法的回调中,但这两种方法都不起作用。

请帮帮我,我被困在回调的地狱里了!

将函数更改为以下内容修复了此问题。

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);
        }
    );
}

不确定,但我认为是将callback的一次出现更改为cb才成功的。

这是一个范围问题,他们感到困惑吗?