【问题标题】:How to pass variable through promise chain using finally如何使用finally通过promise链传递变量
【发布时间】:2019-11-20 12:38:33
【问题描述】:

我正在尝试为 Express API 构建日志,但是在将数据注销时遇到问题。

我可以在finally 块中记录原始req 和res 对象,但我不确定如何访问SQL response。

const sql = require("mssql")
const config = require("../config")

router.get("/express-route", (req, res) => {
  sql.connect(config.properties).then(pool => {
    return pool.request()
      .input('username', sql.NVarChar(32), req.params.username)
      .execute('do_something_with_username')
      .then(response => res.send(response) // pass this response
      .catch(err => res.send(err))
      .finally(() => {
        console.log('response', response)  // to here
        sql.close()
      })
  })
}

如何从第一个 then 块获取响应并将其传递给 finally 块以用于另一个函数?

【问题讨论】:

  • 你不能 - 如果 request 或 input 或 execute 有错误,finally 回调运行但从来没有 response 值。那么你到底想达到什么目的呢?
  • @Bergi 尝试捕获请求正文、请求标头、响应正文等数据以写入 SQL 日志。
  • 您应该在发送响应时写入该日志,而不是在处理错误之后。如果出现错误,您当然需要将不同的数据捕获到您的日志中。 finally 不适合这样做
  • 除了then 之外,我还可以使用其他动词来帮助打破日志范围内的视觉流吗?
  • "then" 通常被归类为副词,而不是动词 :-)

标签: javascript node.js express promise


【解决方案1】:

finally 回调不会接收任何参数,因为没有可靠的方法来确定 promise 是被实现还是被拒绝。此用例正是针对您不关心拒绝原因或履行价值的情况,因此无需提供它。 (mdn)

相反,只需使用.then:

const sql = require("mssql")
const config = require("../config")

router.get("/express-route", (req, res) => {
  sql.connect(config.properties).then(pool => {
    return pool.request()
      .input('username', sql.NVarChar(32), req.params.username)
      .execute('do_something_with_username')
      .then(response => {res.send(response); return response;}) // pass this response
      .catch(err => res.send(err))
      .then(response => {
        console.log('response', response)  // to here
        sql.close()
      })
  })
}

【讨论】:

  • 太棒了。谢谢!!
  • 如果出现错误,不要忘记response 将是undefined,因为这是catch 处理程序返回的内容。
【解决方案2】:

事实上,您可以通过在异步函数中编写代码来简化事情

const sql = require("mssql")
const config = require("../config")

router.get("/express-route", (req, res) => {
  sql.connect(config.properties).then(async pool => {
    try {
        const response = await pool.request()
                         .input('username', sql.NVarChar(32), req.params.username)
                         .execute('do_something_with_username');

        // do another request
        const otherResponse = await pool.request() ... ;

        res.send(response);
    } catch (err) {
        res.send(err);
    } finally {
        sql.close();
    }
  })
}

这可以让您以更线性的方式编写代码。

【讨论】:

  • 想法是用另一个pool.request...替换`console.log('response', response)`来写回SQL...
  • 你可以这样做,就像我在回答中第一个 pool.request 那样调用
  • 感谢您的反馈!! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 2017-10-29
相关资源
最近更新 更多