节点JS |循环等待回调?

时间:2017-01-12 14:29:10

标签: javascript node.js

我有一个我必须循环的数组。我不能使用for循环,因为它是异步的并且它具有回调函数。我将不得不使用等待回调的循环。这可能吗?

代码:

        if ( bots[1].getInventory().getItems().length < capacity ){  
            var executed = false;
            bots[1].createDeposit({
                steamid: req.query.steamid,
                token: req.query.token,
                itemsFromThem: uniqueItems,
                message: req.query.message,
                callback: function( err, dbTradeId ){
                    if ( !executed ){
                        executed = true;
                        if ( !err && dbTradeId ){
                            res.json({ result: 1, dbTradeId: dbTradeId });
                        } else {
                            console.log('» Tried to create deposit, but',err);
                            myMessages.push("Problem");
                            res.json({ error: err });                   
                        }
                    }
                }
            });
        } else {
            console.log('» Tried to create deposit, but no bot found(2)');
            myMessages.push("Available bot not found(2)");
        }

我的问题不是重复,因为我不希望它遍历数组中的每个项目。只有在成功回调之后才会执行。

此致

2 个答案:

答案 0 :(得分:0)

您必须查看async#each。它允许您对阵列列表或循环运行异步调用,并为您提供在所有异步调用完成后运行方法的位置。

// Should give you an idea how to use it
async.each(bots, function (item, callback) {
  if ( item.getInventory().getItems().length < capacity ){  
        var executed = false;
        item.createDeposit({
            steamid: req.query.steamid,
            token: req.query.token,
            itemsFromThem: uniqueItems,
            message: req.query.message,
            callback: function( err, dbTradeId ){
                if ( !executed ){
                    executed = true;
                    if ( !err && dbTradeId ){
                         callback(null, { result: 1, dbTradeId: dbTradeId });
                       // res.json();
                    } else {
                        console.log('» Tried to create deposit, but',err);
                        myMessages.push("Problem");
                        callback(err);                  
                    }
                }
            }
        });
    } else {
        console.log('» Tried to create deposit, but no bot found(2)');
        myMessages.push("Available bot not found(2)");
    }
}, function (err) {
  console.log('All done');
});

答案 1 :(得分:0)

您可以创建另一个promises数组,然后使用Promise.all等待它们完成。我不知道你需要迭代的来源,但我们假设你想建立一个http连接:

const yourThingies = [
    "http://a-server.com/",
    "http://www.another.com/"
    //And so on...
];
let promises = [];

yourThingies.forEach( (url) => {
    const p = new Promise((resolve, reject) => {
        //Call this on resolve, or use something that returns a promise.
        resolve("your data");
    });
    promises.push(p);
});

Promise.all(promises).then((solvedPromises) => {
   //Do things once all is done
       solvedPromises.forEach((solv) => {
            //So on...
       });
});

有关Promise Promise MDN Docs

的更多信息

编辑: 注意:当我回答没有代码时,我会尝试编辑。