mongodb函数的异步回调

时间:2017-08-10 06:44:35

标签: javascript node.js mongoose

我正在尝试使此功能进行适当的回调。在编写时,回调将被调用两次 - 一次用于同步'if'语句,一次用于异步'test2.save'语句。我把计数器代码放在我试过的例子中。它不起作用,因为底部的if语句是同步的。我已经知道这段代码有什么问题,但我不知道如何让它更好。

var postMatches = function(user1, userResults, callback) {
  User.find({}, {username: 1, testResults: 1}, (err, users) => {
    var counter = 0;
    users.forEach(function(user2){
      counter++;
      if(user1 !== user2.username && user2.testResults !== undefined) {
        var test1 = new Test({
          username: user1,
          match: user2.username,
          compatability: mbti[userResults][user2.testResults],
          alreadyMatches: false
        });

        test1.save( () => {
          var test2 = new Test({
            username: user2.username,
            match: user1,
            compatability: mbti[user2.testResults][userResults],
            alreadyMatches: false
          });

          test2.save( () => {
            if(counter === users.length) {
              callback();
            }
          });
        })
      } else {

        if(counter === users.length) {
          callback();
        }
      }
    })
  })
};

1 个答案:

答案 0 :(得分:1)

从评论和问题中,编写了一个代码。使用async模块和forEach函数迭代用户列表并在完成后返回回调。阅读有关async和forEach的信息。如果这适用于您的用例,请告诉我。

var async = require('async')
var postMatches = function(user1, userResults, callback) {
  User.find({}, {username: 1, testResults: 1}, (err, users) => {
    var counter = 0;
    async.forEach(users,function(user2,iterate_callback){
      if(user1 !== user2.username && user2.testResults !== undefined) {
        var test1 = new Test({
          username: user1,
          match: user2.username,
          compatability: mbti[userResults][user2.testResults],
          alreadyMatches: false
        });

        test1.save( () => {
          var test2 = new Test({
            username: user2.username,
            match: user1,
            compatability: mbti[user2.testResults][userResults],
            alreadyMatches: false
          });

          test2.save( () => {
            iterate_callback();
          });
        })
      } else {
        iterate_callback();
      }
    },function(err){
      console.log("Done iterating");
      return callback();
    });
  })
};