callback无法正常工作node.js

我正在一个for循环执行一个MySQL查询,这个循环是在callback函数,但是当我做console.log(我),它显示我三次。 下面是代码。 我正在使用async.parallel,我只发布有问题的代码。 res也返回正常,但obj显示第三个logging三次,而不是显示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。 任何帮助真的很感激。

这是因为asynchronous调用。 当你的电话结束时, 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); } 

其实你的callback工作正常。

你的数据库查询很可能是asynchronous的。 这意味着当你从你的数据库中获得信息时, i已经等于3了。

您最终可以使其同步: 使用Node.js进行同步数据库查询