【问题标题】:How to pass request object through promise chain如何通过承诺链传递请求对象
【发布时间】:2020-04-28 15:39:26
【问题描述】:
我正在尝试使用 Node.js mssql 包将请求对象作为 then 语句的一部分。
但是,当我尝试将其注销时,它是未定义的。
exports.someFunction = (proc, req, res) => {
sql.connect(config.properties).then((pool, req) => {
return pool.request()
.execute(proc)
.then((response, req) => {
console.log(req) // undefined
})
}
如何将请求对象传递给then 语句进行比较?
【问题讨论】:
标签:
node.js
sql-server
scope
es6-promise
【解决方案1】:
您已将三个单独的函数参数定义为 req,因此它们都相互隐藏,并且您尝试为不存在的 .then() 处理程序声明第二个参数,因此它当然是 @987654323 @。
您可以直接访问父作用域中的变量,这就是您在此处需要做的所有事情:
exports.someFunction = (proc, req, res) => {
return sql.connect(config.properties).then((pool) => {
return pool.request()
.execute(proc)
.then((response) => {
console.log(req) // can directly access the req in the parent scope
// do something with `req` here
})
}
【解决方案2】:
如果您想保持范围,也许更好的方法是将其编写为 async/await:
exports.someFunction = async (proc, req, res) => {
const pool = await sql.connect(config.properties)
const result = await pool.request().execute(proc)
console.log(result, req) // both retain scope
})
}
但我认为 req 在您的 console.log 中未定义的原因是因为:
sql.connect(config.properties).then((pool, req) => {
您期望 req 作为 .then() (这是一个阴影变量)的结果传递给您。如果您将其从此处和其他 .then() 删除,那么它也应该可以工作