gpt4 book ai didi

javascript - 如何在 Node js中的foreach之后发送响应?

转载 作者:行者123 更新时间:2023-11-30 14:27:12 25 4
gpt4 key购买 nike

在我的 foreach 中,我想将数据推送到数组中并将响应发送到客户端。

我正在使用以下内容:

try {
var allData = [];
var venuesData = req.db.collection('venues').find({ "restaurantcompetitors": {$exists: true, $ne: null } }, {restaurantcompetitors:1});

venuesData.forEach(function(data) {
Array.prototype.push.apply(allData, data);

res.status(200).send({data: allData, code: 0});
});

}
catch (error) {
console.log('Error found in catch: ',error);
}

但是我收到一个错误“header already sent”,因为我在循环内发送。但是如果我尝试在循环后推送数据,它就无法推送...

最佳答案

您实际上需要使用 promise 或使用 async/await

在此处阅读有关异步代码和 promise 的更多信息 - https://medium.com/dev-bits/writing-neat-asynchronous-node-js-code-with-promises-32ed3a4fd098

更多关于 async/await 的信息 - https://blog.risingstack.com/mastering-async-await-in-nodejs/

try {
var allData = [];
var venuesData = await req.db.collection('venues').find({
"restaurantcompetitors": {
$exists: true,
$ne: null
}
}, {
restaurantcompetitors: 1
});

// This code won't run until the venuesData has resolved
venuesData.forEach(function (data) {
Array.prototype.push.apply(allData, data);


});
//Need to send after you have done the loop
res.status(200).send({
data: allData,
code: 0
});

} catch (error) {
console.log('Error found in catch: ', error);
}

关于javascript - 如何在 Node js中的foreach之后发送响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51744267/

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