【问题标题】:how to force a for loop to wait a callback to finish in nodejs?如何强制 for 循环等待回调在 nodejs 中完成?
【发布时间】:2017-03-27 13:48:30
【问题描述】:
entry.find(function(err,user){
  for(var i=0;i<user.length;i++){
    if(user[i].tablenumber==-1){

       assigntable(user[i]);
    }
  }

});

所以我在这里尝试做的是在调用异步可分配函数之前等待每个 for 循环完成。 Assigntable 是对数据库进行更改的回调。 我现在遇到的问题是因为在 for 循环完成后调用了 assigntable 的回调,所有用户都将被分配到表 1。 但我想要的是:将第一个分配给表 1-> 在下一个循环中分配表检测到表 1 已分配-> 用户 2 分配给表 2,依此类推。 我该怎么做?

Edit:Assgintable 是一个递归调用,它在回调中编辑数据库。更新将基于前一个循环生成的数据库的结果,但我在这里不相关。

  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);
  }
})

}

【问题讨论】:

  • assigntable() 是否返回 Promise
  • 只是为了澄清-您希望在调用 user[1] 的 assigntable 之前完成 user[0] 的 assigntable 吗?关于递归的评论也有点混乱,你能包括更多的代码来澄清吗?
  • @skav 是的,我希望在调用 user[1] 的 assigntable 之前完成 user[0] 的assigntable

标签: node.js mongodb asynchronous


【解决方案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});

【讨论】:

猜你喜欢
  • 2014-07-19
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多