gpt4 book ai didi

javascript - forEach 的简单 promise

转载 作者:搜寻专家 更新时间:2023-10-31 23:52:51 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com