如何强制for循环等待callback完成在nodejs?

entry.find(function(err,user){ for(var i=0;i<user.length;i++){ if(user[i].tablenumber==-1){ assigntable(user[i]); } } }); 

所以我在这里要做的是在调用asynchronousassigntable函数之前等待每个for循环完成。 Assigntable是对数据库进行更改的callback。 我现在的问题是,因为asscomntable的callback是在for循环完成后调用的,所有的用户都会被分配到表1中。但是我想要的是:将第一个分配给表1 – >在下一个循环中分配表1被分配 – >用户2被分配到表2等等。 我怎么做?

编辑:Assgintable是一个recursion调用,在callback中编辑数据库。 更新将基于从前一个循环产生的数据库的结果,但我没有在这里相关。

  function assigntable(user,tableindex){ console.log("in recursion with tableindex"+tableindex); if(tableindex==3) return; console.log(user.date+user.time+tableindex); entry.find({ $and: [ { "tablenumber": tableindex}, { "date": user.date }, {"time":user.time} ] },function(err, result) { if(result.length==0){ console.log(result+"result is "); entry.update({"_id":user._id},{"tablenumber":tableindex},function(err, numberAffected) { if(!numberAffected){ } else { console.log("entryupdated with "+tableindex) } }); return; } else{ console.log(tableindex); assigntabe(user,tableindex+1); } }) 

}

你可以使用async.foreach来同步迭代:

 entry.find(function(err,user){ async.forEach(user, function (item, callback){ if(item.tablenumber==-1){ console.log(item); assigntable(item,1); } callback(); }, function(err) { console.log('iterating done'); })}).sort({datesubmitted:1});