我正在尝试为 Express API
构建日志,但是在注销数据时遇到问题。
我可以在 finally
block 中记录原始的 req
和 res
对象,但不确定如何访问 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/