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

}

S.W
  • 21
  • 7
  • Does `assigntable()` return a `Promise`? – CodingWithSpike Nov 13 '16 at 23:43
  • just to clarify - you want assigntable for user[0] to finish before assigntable for user[1] is called? the comment about the recursion is a bit confusing also, can you include more code to clarify? – skav Nov 13 '16 at 23:43
  • @skav yes I want assigntable for user[0] to finish before assigntable for user[1] is called – S.W Nov 13 '16 at 23:52

1 Answers1

1

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});
Nir Levy
  • 12,750
  • 3
  • 21
  • 38
  • I tried but its not working. the callback in assigntable function starts only after the for loop finishes. – S.W Nov 14 '16 at 00:09
  • related for more context: http://stackoverflow.com/questions/21184340/async-for-loop-in-node-js – Lance Nov 14 '16 at 01:34