【发布时间】:2019-05-05 07:40:54
【问题描述】:
使用下面的代码我得到了这个错误:
Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 如果result === null。
'use strict'
const HttpStatus = require('http-status-codes')
const { handleErr } = require('ciitizen-express-helpers').utils
function updateOrganization(db, stats) {
return function (req, res) {
db.organization.findOne({
where: {
id: req.params.id
}
})
.then(result => {
if (result === null) {
return res.status(HttpStatus.NOT_FOUND).send() <-- IF RESULT IS NULL, I RETURN THIS
}
console.log('original result = ', result)
// Update any fields that were passed in
if (req.body.name) {
result.name = req.body.name
}
if (req.body.address1) {
result.address1 = req.body.address1
}
if (req.body.address2) {
result.address2 = req.body.address2
}
if (req.body.city) {
result.city = req.body.city
}
if (req.body.state) {
result.state = req.body.state
}
if (req.body.zip) {
result.zip = req.body.zip
}
console.log('new result = ', result)
return result.save()
})
.then(result => {
console.log('final result = ', result)
return res.status(HttpStatus.CREATED).send(result) <-- BUT IT'S STILL TRYING TO CALL THIS, HENCE THE CAN'T SEND HEADERS ERROR
})
.catch(err => {
req.log.error(err)
return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
})
}
}
module.exports = updateOrganization
在不继续我的承诺链流程的情况下尽早返回响应的最佳方式是什么?
【问题讨论】:
-
IF RESULT IS NULL, I RETURN THIS...BUT IT'S STILL TRYING TO CALL THIS当然是...这就是承诺链的工作原理...我建议在res.status(HttpStatus.NOT_FOUND)之后返回null...并在@987654328 @检查结果是否为空,如果是,跳过res.status(...代码
标签: javascript node.js express promise