NodeJS - For循环 - 等待回调继续

时间:2015-05-30 20:00:48

标签: mysql node.js

我正在尝试查询,foreach数组中的id,来自MySQL数据库的一些数据。 我的for循环看起来像下面的

for(var i = 0; i < res.length; i++) {
    var steamid = res[i].steamid;
    db.query('SELECT `name` FROM `users` WHERE `steamid`=?', [steamid], function(err, rows) {
        var player = {name: rows[i].name};
        team.push(player);
    });
}

但问题是for循环在查询完成之前继续,然后var i已经增加了一两个。

有没有办法检查查询是否已完成?

1 个答案:

答案 0 :(得分:2)

只需使用closure,以便您的i引用正确的索引。

function finished(){...}//called when you fetched all your data
var nbDone = 0;
res.forEach(function(elem, i){
    var steamid = elem.steamid;
    db.query('SELECT `name` FROM `users` WHERE `steamid`=?', [steamid], function(err, rows) {
        var player = {name: rows[i].name};
        team.push(player);
        nbDone++;
        if(nbDone == res.length){
          finished();//you know all of your queries have completed
        }
    });
});

您可能希望查看promises或async以处理异步流程