我试图查询数组中的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
已经增加了一两个。有没有一种方法可以检查查询是否已完成?
最佳答案
只需使用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
}
});
});
您可能需要查看Promise或async以处理异步流
关于mysql - NodeJS-For循环-等待回调继续,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30550779/