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

}

3
  • Does assigntable() return a Promise? Commented Nov 13, 2016 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? Commented Nov 13, 2016 at 23:43
  • @skav yes I want assigntable for user[0] to finish before assigntable for user[1] is called Commented Nov 13, 2016 at 23:52

1 Answer 1

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});
Sign up to request clarification or add additional context in comments.

2 Comments

I tried but its not working. the callback in assigntable function starts only after the for loop finishes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.