javascript - 如何使用finally通过promise链传递变量

标签 javascript node.js express promise

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

我可以在 finally block 中记录原始的 reqres 对象,但不确定如何访问 SQL 响应

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 block 获取响应并将其传递到 finally block 以便在另一个函数中使用?

最佳答案

A finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it. (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()
      })
  })
}

关于javascript - 如何使用finally通过promise链传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56978256/

相关文章:

javascript - 如何在没有 iFrame 的情况下在 html 上显示来自另一台服务器的 PHP 页面?

Javascript 不会更新 session ,只有页面重新加载才能完成这项工作

javascript - Jam vs Bower,有什么区别?

node.js - 使用 Express req.query 序列化查询

javascript - express.js 路由器中的自定义处理程序

javascript - 鼠标悬停时发出声音,鼠标悬停时停止

javascript - 更改从文本文件读取的js文件的样式

javascript - 使用 aws Secret Manager 配置 knexfile.js

javascript - Hello.js 与 Passport.js?

javascript - 无法获取 ejs 文件