如何使用承诺结果的响应处理程序

How to use a response handler for promise results

我有两个具有共同响应逻辑的方法,我试图将该响应逻辑提取到另一个方法并 link 到所有承诺,但确实抛出了错误:

原始方法:

  method1: function (req, res) {
    db.getData(req)
      .then(data => {
          res.status(200).send({ status: 200, data: data })
      })
      .catch(error => {
        res.status(500).send({ status: 500, statusText: error.message })
      })
  },
  method2: function (req, res) {
    db.getData2(req)
      .then(data => {
          res.status(200).send({ status: 200, data: data })
      })
      .catch(error => {
        res.status(500).send({ status: 500, statusText: error.message })
      })
  },

我试图做什么? (将response promise提取到另一种常用方法)

responseMethod: function (promise) {
    promise
      .then(data => {
        res.status(200).send({ status: 200, data: data })
      })
      .catch(error => {
        res.status(500).send({ status: 500, statusText: error.message })
      })
  },
  method1: function (req, res) {
    responseMethod(db.getData(req))
  },
  method2: function (req, res) {
    responseMethod(db.getData2(req))
  },

错误:

Reference Error: responseMethod is not defined

我找到了解决这个问题的方法:

回答如下:

fix #1: res as a parameter in the responseMethod

fix #2: return of the promise in the responseMethod

responseMethod: function (res, promise) {
    return promise
      .then(data => {
        res.status(200).send({ status: 200, data: data })
      })
      .catch(error => {
        res.status(500).send({ status: 500, statusText: error.message })
      })
  },
  method1: function (req, res) {
    responseMethod(res, db.getData(req))
  },
  method2: function (req, res) {
    responseMethod(res, db.getData2(req))
  },

Reference Error: responseMethod is not defined

您的错误与 javascript 中的 this 关键字有关,与任何异步内容无关。

const containerObj = {
  responseMethod: function() {
    return 'ok'                  // simplified for testing
  },
  method1: function() {
    return this.responseMethod() // succeeds because it references 'this' object
  },
  method2: function() {
    return responseMethod()      // fails because you need to reference 'this'
  },
}

/* TESTS */
console.log(containerObj.method1()) // should succeed
console.log(containerObj.method2()) // should fail

希望这对您有所帮助。 干杯,