我正在尝试使用 Promise 来等待异步 forEach:
var forEachMatch = function(matches) {
var deferred = Q.defer();
matches.forEach(function(match) {
var messages = Message.find({'matchid': match._id}, function(err,messages) {
if(err)
console.log(err);
else
console.log(match._id);
});
});
return deferred.promise;
};
在这里使用:
forEachMatch(matches, function() {
console.log("DONE");
res.status(200).json({
bob,
matches: matches,
});
});
我的控制台输出如下:所有 match._id
都已打印,但 DONE
从未打印。
有什么办法可以解决吗?我从 node 和 promises 开始,所以我当然忘记了一些东西,但我没有看到什么。
感谢您的任何回答。
编辑
最终的解决方案,感谢 Alexander Mac:
var forEachMatch = function(matches) {
var promises = matches.map(match => {
return Message
.find({'matchid': match._id})
.populate({
path: 'fromUser toUser',
select: 'id firstname'
})
.then(messages => [match, messages])
.catch(err => {
console.log("Error in forEachMatch");
return [match, null];
});
});
return Q.all(promises);
}
forEachMatch(matches)
.then(messagesByMatch => {
res.status(200).json({
user,
messagesByMatch: messagesByMatch
});
});
最佳答案
在您的情况下,使用 Q.all
可以更好地匹配,它接受 promise 或值的数组:
var forEachMatch = function(matches) {
var promises = matches.map(match => {
return Message
.find({'matchid': match._id})
.then(messages => [match, messages]);
});
return Q.all(promises);
}
forEachMatch(matches)
.then(results => {
console.log("DONE", results);
res.status(200).json({
bob,
matches: matches,
});
});
https://github.com/kriskowal/q/wiki/API-Reference#promiseall
关于javascript - forEach 的简单 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36859382/