简体   繁体   中英

using Async.each refuses to call the final callback

in the following code I am expecting the function finalCallBack to be executed once we are done iterating through all elements

var rows = [
  { name: 'first'},
  { name: 'second'}
];

var execForEachRow = function(row, callback){

  var studentModel = new StudentModel(row);
  studentModel.save(function(err,result){
    if (err) { throw err;}
    rowsSavedCount++;
  });
}

var finalCallBack = function(err){
  if (err) { msg = err;} else { msg = rowsSavedCount;}
  res.send({"result" : msg});

}

async.each(rows, execForEachRow, finalCallBack);

When i execute the above code, it very successfully inserts data into the mongo collection. However the finalCallBack does not get called.

Any clue what I might be missing here ?

You've missed calling callback in studentModel.save 's callback:

studentModel.save(function(err,result){
    if (err)        
       return callback(err);
    rowsSavedCount++;
    callback(null);
});

Also - throwing Exception is not a good idea - it'll break you whole Express server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM