在 forEach() 函数中完全脱离 post 请求
Completly break out of post request while being in forEach() function
下面的代码是 node.js 后端的 try catch 块的摘录。如果缺少 req.body
的一项,我想跳出完整的 post 请求。我认为现在 return res
仅从导致 [ERR_HTTP_HEADERS_SENT] 错误的 forEach()
函数中断,因为它稍后会发送另一个响应。
Object.values(req.body).forEach(value=>{
if (!value) {
return res
.json({
message: "You are missing personal information.",
success: false
})
.status(500);
}
});
// stop this code from running
function generateUser(name) {
const {doc, key} = new Document(KeyType.Ed25519)
return {
doc,
key,
name,
}
}
...
引用自MDN:
“除了抛出异常之外,没有其他方法可以停止或中断 forEach() 循环。如果您需要这种行为,forEach() 方法是错误的工具。”
所以您不能按照您尝试的方式使用 forEach 循环,而应该使用某事。像 Array.prototype.find
,例如像这样:
const reqIsIncomplete = Object.values(req.body).find(value => !value);
if (reqIsIncomplete) {
return res
.json({
message: "You are missing personal information.",
success: false
})
.status(500);
}
下面的代码是 node.js 后端的 try catch 块的摘录。如果缺少 req.body
的一项,我想跳出完整的 post 请求。我认为现在 return res
仅从导致 [ERR_HTTP_HEADERS_SENT] 错误的 forEach()
函数中断,因为它稍后会发送另一个响应。
Object.values(req.body).forEach(value=>{
if (!value) {
return res
.json({
message: "You are missing personal information.",
success: false
})
.status(500);
}
});
// stop this code from running
function generateUser(name) {
const {doc, key} = new Document(KeyType.Ed25519)
return {
doc,
key,
name,
}
}
...
引用自MDN:
“除了抛出异常之外,没有其他方法可以停止或中断 forEach() 循环。如果您需要这种行为,forEach() 方法是错误的工具。”
所以您不能按照您尝试的方式使用 forEach 循环,而应该使用某事。像 Array.prototype.find
,例如像这样:
const reqIsIncomplete = Object.values(req.body).find(value => !value);
if (reqIsIncomplete) {
return res
.json({
message: "You are missing personal information.",
success: false
})
.status(500);
}