我在for循环内执行mysql查询,此循环在回调函数中,但是当我执行console.log(i)时,它向我显示3次3次。下面是代码。我正在使用async.parallel,我只发布有问题的代码。res也返回正常,但是obj显示了第三次记录,而它必须显示obj1数据,obj2数据和obj3数据。console.log(i)是示例响应。
function(user,callback){
for(var i = 0; i < user.length ; i++) {
var obj = user[i];
mySQLConn.mySQLDBConnection.query('select id,name from table where type = ?',[obj.id],function(err,res){
console.log(i); //This shows 3 three times
obj.type = res;
userJSONArray.push(obj);
})
}
}
我想要的应该打印1,2,3而不是3,3,3。非常感谢任何帮助。
这是由于异步调用。到您的通话结束时,其中i
有3个...您可以执行以下操作:
for(var i = 0; i < user.length ; i++) {
var obj = user[i];
(function(i, obj)
{
mySQLConn.mySQLDBConnection.query('select id,name from table where type = ?',[obj.id],function(err,res){
console.log(i); //This shows 3 three times
obj.type = res;
userJSONArray.push(obj);
})
})(i, obj);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句