在mongodb函数上的asynchronouscallback

我正在试图使这个function作出适当的callback。 按照写法,callback将被调用两次 – 一次用于同步“if”语句,一次用于asynchronous“test2.save”语句。 我正在把计数器代码作为我尝试的一个例子。 如果声明是同步的,那么它不起作用。 我已经知道这个代码有什么问题,但我不知道如何使它更好。

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(); } } }) }) }; 

从评论和问题,在这里编写一个代码。 使用asynchronous模块和forEach函数遍历用户列表并返回一次完成的callback。 阅读有关asynchronous和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(); }); }) };