gpt4 book ai didi

javascript - Express Promise Chain如何发送响应并结束Promise Chain流程?

转载 作者:行者123 更新时间:2023-12-01 01:27:43 24 4
gpt4 key购买 nike

使用下面的代码我收到此错误:

未处理的拒绝错误 [ERR_HTTP_HEADERS_SENT]:如果 result === null,则在将 header 发送到客户端后无法设置 header

'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

在不继续我的 promise 链流程的情况下提前返回响应的最佳方式是什么?

最佳答案

像这样的 promise 链

你能做的是

A) res.status(HttpStatus.NOT_FOUND) 之后return null(删除该代码之前的return)

B) in then(result) 检查 result 是否为 null,如果是,则跳过 res.status(... 代码

例如

'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) {
// change A
res.status(HttpStatus.NOT_FOUND).send();
return null;
}
// snip
return result.save()
})
.then(result => {
console.log('final result = ', result)
// change B
if (result !== null) {
return res.status(HttpStatus.CREATED).send(result)
}
})
.catch(err => {
req.log.error(err)
return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
})
}
}

module.exports = updateOrganization

或者,保留现有代码直到

      .then(result => {
// change C
if (!res.headersSent) {
console.log('final result = ', result)
return res.status(HttpStatus.CREATED).send(result)
}
})

说实话,这可能是一个“更干净”的修复

关于javascript - Express Promise Chain如何发送响应并结束Promise Chain流程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53603460/

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