如何在节点js

时间:2015-08-20 16:00:46

标签: node.js asynchronous

嗨,我有这段代码,但完成后结果不受尊重,因为没有按照我希望的顺序运行

这是代码:

var user_data = {};    
models.games.find({$or: [{w_id: req.user._id}, {b_id: req.user._id}, {owner: req.user._id}]}, function (err, games) {
        var req_games = [];
        if (!err) {
            for (var i in games) {
                req_games.push(games[i]);
                models.users.findOne({_id: games[i].w_id}, function (err, user) {
                    req_games[i].w_id = user.user;
                    console.log(req_games[i].w_id) //< -- 3
                });
                console.log('a ' + req_games[i].w_id) //<-- 2
            }
            user_data.games = req_games; //  <-- 1
        }
    });

在任务结束时req_games没有任何更新,因为它按照我在代码中的注释中放入的顺序运行

2 个答案:

答案 0 :(得分:2)

这可以帮助您使用Q(承诺)

obj.find = function(model, condition) {  //make your find to return promise
        var deferred = q.defer();
        model.find(condition, function(err, results) {
          if (err) {
            logger.log(err);
            deferred.reject(err);
          } else {
            deferred.resolve(results);
          }
        });
        return deferred.promise;
      }


     ArraysOfId.forEach(function (id) {
          var tempProm = mongoUtilsMethodObj.find(schemaObj.Asset, id).then(function (assetObj) {
            ---- your code

            return q.resolve();
          });
          promArr.push(tempProm);//push all promise to array
        });

        q.all(promArr).then(function () {
         // this will be called when all promise in array will we resolved


          })

答案 1 :(得分:1)

以下是使用this库来映射游戏价值的版本。​​

var async = require('async');

var user_data = {};  
models.games.find({$or: [{w_id: req.user._id}, {b_id: req.user._id}, {owner: req.user._id}]}, function (err, games) {
  if(err) {
    // or whatever your error response happens to be
    return res.render('user.swig', {error: err});
  }

  async.map(games, function(game, nextGame) {
    models.users.findOne({_id: game.w_id}, function (err, user) {
      game.w_id = user.user;
      nextGame(err, game);
    });
  }, function(err, req_games) {
    user_data.games = req_games;
    res.render('user.swig', {user: user_data});
  });
});