簡體   English   中英

表達承諾鏈如何發送響應並終止承諾鏈流程?

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

與下面的代碼,我得到這個錯誤:

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

在不繼續履行承諾鏈流程的情況下,盡早返回響應的最佳方法是什么?

這樣的承諾鏈

你能做的是

A)在res.status(HttpStatus.NOT_FOUND) )之后return null (刪除該代碼之前的return

B) then(resultthen(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)
        }
      })

老實說,這可能是“更清潔”的解決方案

測試一下:

    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