我如何像同步方法一样调用异步方法?

时间:2016-03-31 19:51:49

标签: javascript node.js promise

我在promises.js中使用node.js和mongoDB。我必须在promise变量中调用异步方法,但我不能创建另一个而不是()。因为它处于循环中。代码就像:

collection1.find({'key': 'value'})
            .then(function(matches){
               //loop starts
                matches.forEach(function(match){
                    var currentUser = collection2.find({"_id" : match._user})
                    console.log(currentUser); //undefined
                })
}) 

正如您所见,currentUser是一个未定义的变量。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以使用deep-populate

async也可以运作:

function processMatch(match, cb) {
  collection2.findOne({"_id":match._user}).then(function(user) {
    cb(null, user);
  });
}
collection1.find({'key':'value'})
  .then(function(matches) {
    var async = require('async');
    async.mapLimit(results.results, NUMBER_OF_PARALLEL_REQUEST, processMatch, function(err, users) {
      users.forEach(function(currentUser) {
      });
    });
  });