简体   繁体   中英

Async parallel final callback doesn't fire

I do have a async parallel block to execute two queries into MongoDB. on each step of function(callback) I have a valid return result, no any errors are firing. I did debug and all steps are working except that final callback not firing and I can't event reach with breakpoint to its condition. Does anybody have idea what that may happen?

async.parallel([

// first Query
function(callback){
  this._game.findOne({'_id': gameId}, function(err, result){
    if(err){return callback(err);}
    else if(result) {
      callback(null, result);
    }
  });
},

// second Query
function(callback){
  this._player.findOne({'_id': playerId}, function(err, result){
    if(err){return callback(err);}
    else if(result) {
      callback(null, result);
    }
  });
}
],

  // Final callback to send all 2 Results -> which is not working...
  function(error, results){

    if(results){

      res.status(200);
      res.send(results);
    }
  }
);`

You're not dealing with the possibility that Mongo doesn't find any results. In this case it will call the callback with err and result as null. When this happens the functions that you're running in parallel don't call their callbacks, so the final function never runs. What you do in this case is up to you but you need to call the callback function with something.

The reason that you're not getting any results is most likely that playerId and gameId are strings and _id is by default an ObjectId. Add a var ObjectId = require('mongodb').ObjectId; , then replace playerId with ObjectId(playerId) and you'll likely see results.

This is how i would debug it :

async.parallel([

// first Query
function(fq_callback){
  this._game.findOne({'_id': gameId}, function(fq_err, fq_result){
    if(fq_err){
      console.log('err from _game.findOne');
      return fq_callback(fq_err);
    }
    else if(fq_result) {
      console.log('result from _game.findOne');
      fq_callback(null, fq_result);
    }
  });
},

// second Query
function(sq_callback){
  this._player.findOne({'_id': playerId}, function(sq_err, sq_result){
    if(sq_err){
      console.log('err from _player.findOne');
      return sq_callback(sq_err);
    }
    else if(sq_result) {
      console.log('result from _player.findOne');
      sq_callback(null, sq_result);
    }
  });
}
],

  // Final callback to send all 2 Results -> which is not working...
  function(fn_error, fn_results){
    console.log('in final callback');
    if(fn_error) console.log('we have error');
    if(fn_results){
      console.log('we have results');
      res.status(200);
      res.send(results);
    }else{
      console.log('we have NO results');
    }

  }
);

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