Tuesday 11 April 2017

Callback not getting called while using collection.save() in async foreach loop in node js

My aim is to save records in a mongoDB collection being in a async foreach loop. Below is the code which speaks for itself.

async.forEach(data, function(item, callback) {
      var object = new Collection_Object();

      // errorLog.push(sdb);
      object.save(function(error) {
        count++;
        console.log(count);
        if(error) {
          console.log("inside error");
          count--;
        }
        //callback();
      });
      callback();
    }, function() {
    //This is the block which should be called after foreach. 
      res.json(data);
  });

Now what is happening is the flow skips the save part and directly jumps to the block which should be called after forEach.

If i am commenting the save part, as expected the callback is working properly. I don't see where i am doing mistake. May be collection.save() isn't suppose to be like this. Please guide.



via this_is_sagar

No comments:

Post a Comment