S.W
S.W

Reputation: 21

how to force a for loop to wait a callback to finish in nodejs?

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

       assigntable(user[i]);
    }
  }

});

so what I am trying to do here is to wait for each for loop to finish before calling the asynchronous assigntable function. Assigntable is a callback to make changes to the database. The problem I have right now is since assigntable's callback is called after the for loop finishes, all the user will be assigned to table 1. But what I want is : assign the first one to table 1 -> assign table in next loop detects table 1 is assigned ->user 2 assigned to table 2 and so on. How do I do that?

Edit: Assgintable is a recursive call that edits the database in a callback. the update will be based on the result of the resulting database from the previous loop, but I don't its relevant here.

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

}

Upvotes: 2

Views: 2182

Answers (1)

Nir Levy
Nir Levy

Reputation: 12953

you can use async.foreach in order to iterate synchronously:

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

Upvotes: 1

Related Questions