简体   繁体   English

表达承诺链如何发送响应并终止承诺链流程?

[英]Express promise chain how to send response and end promise chain flow?

With the code below i'm getting this error: 与下面的代码,我得到这个错误:

Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client if result === null . Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client如果result === nullUnhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

'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

What's the best way to return a response early without continuing through my promise chain flow? 在不继续履行承诺链流程的情况下,尽早返回响应的最佳方法是什么?

Promises chain like that 这样的承诺链

What you can do is 你能做的是

A) return null AFTER res.status(HttpStatus.NOT_FOUND) (removing the return before that code) A)在res.status(HttpStatus.NOT_FOUND) )之后return null (删除该代码之前的return

B) in then(result check if result is null, if so, skip the res.status(... code B) then(resultthen(result检查结果是否为null,如果是,则跳过res.status(...

eg 例如

'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

alternatively, keep your existing code until 或者,保留现有代码,直到

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

That's probably a "cleaner" fix to be honest 老实说,这可能是“更清洁”的解决方案

Test this: 测试一下:

    function updateOrganization(db, stats) {
  return function (req, res) {
    db.organization.findOne({
      where: {
        id: req.params.id
      }
    })
      .then(result => {

        if (!result) {
          res.status(HttpStatus.NOT_FOUND).end();
          return null;
        }

        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);
        if(result) {
            return res.status(HttpStatus.CREATED).json(result)
        }
        return null;

      })
      .catch(err => {
        req.log.error(err);
        return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message);
      })
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM