无法解决承诺拒绝并发送数组作为响应 [英] Unable to resolve promise rejection and send array as response
问题描述
我正在尝试内部处理两个查询.
I am trying to handle two queries within each other.
exports.get_users = (req, res) => {
SubscriptionPlan.find()
.then((result) => {
if (!result) {
return res.status(400).json({ message: "unable to process" });
}
let modifiedData = [];
result.forEach(async (data) => {
if (data.processStatus === "active") {
await Users.findById(data.userId).then(
(response) => {
console.log(response)
modifiedData.push(response);
res.json(modifiedData)
}
);
}
});
})
.catch((err) => console.log(err));
};
我的问题就在于,如果我采用这种方法,那么我会得到诺言拒绝的错误:
My issue goes, if I follow this approach, then I get the error for promise rejection:
node:15036) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
还有邮递员收到的 modifiedData
数组的响应,只有长度为3的数组之外的单个对象.语句 console.log(response)
,返回3个需要推送到新数组的对象.
and also, the response of modifiedData
array I receive in postman, only a single object out of array of length 3. The statement console.log(response)
, returns 3 objects that I need to push to new array.
如果我这样更改代码以解决拒绝问题,
If I change my code like this to resolve the rejection,
exports.get_users = (req, res) => {
SubscriptionPlan.find()
.then((result) => {
if (!result) {
return res.status(400).json({ message: "unable to process" });
}
let modifiedData = [];
result.forEach(async (data) => {
if (data.processStatus === "active") {
await Users.findById(data.userId).then(
(response) => {
console.log(response)
modifiedData.push(response);
}
);
}
});
res.json(modifiedData)
})
.catch((err) => console.log(err));
};
它向我返回一个空数组,作为邮递员中的响应.我知道我陷入了JS的异步性质之间,但无法解决此问题.
it returns me an emtpy array as reponse in the postman. I am aware that I am stuck between async nature of JS, but unable to resolve this issue.
PS.在这里,使用async-await对我没有帮助.
PS. Using async-await is not helpful here for me.
任何早期帮助将不胜感激.
Any early help will be appreciated.
推荐答案
result.forEach
返回承诺数组.您需要使用 Promise.all([[])
result.forEach
returns array of promises. You need to promisify all at once using Promise.all([])
exports.get_users = (req, res) => {
SubscriptionPlan.find().then(async (result) => {
if (!result) {
return res.status(400).json({ message: "unable to process" });
}
let modifiedData = [];
await Promise.all(
result.map(async(data) => {
if (data.processStatus === "active") {
const response = await Users.findById(data.userId);
modifiedData.push(response);
}
})
);
return res.json(modifiedData);
}).catch((err) => console.log(err));
};
或者可以一次找到
exports.get_users = async (req, res) => {
try {
const result = await SubscriptionPlan.find({ processStatus: "active" });
if (!result) {
return res.status(400).json({ message: "unable to process" });
}
const ids = result.map(({ userId }) => userId);
const response = await Users.find({ userId: { $in: ids } });
return res.json(response);
} catch (err) {
console.log(err)
return res.status(400).json({ message: "unable to process" });
}
};
这篇关于无法解决承诺拒绝并发送数组作为响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!