如何通过承诺链传递请求对象

时间:2020-04-28 15:39:26

标签: node.js sql-server scope es6-promise

我正在尝试使用Node.js then包将请求对象作为mssql语句的一部分。

但是,当我尝试注销时,它是未定义的。

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语句进行比较?

2 个答案:

答案 0 :(得分:0)

您已经将三个独立的函数参数定义为req,因此它们都相互隐藏,并且您尝试为.then()处理程序声明了第二个参数,但该参数实际上不存在将为undefined

您可以在父级作用域中直接访问变量,因此您只需在这里进行操作:

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
    })
  }

答案 1 :(得分:0)

如果要保留范围,也许更好的方法是将其写为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
})

}

但是我认为在console.log中未定义req的原因是因为:

sql.connect(config.properties).then((pool, req) => {

您期望由于.then()(一个带阴影的变量)而导致req传递给您。如果您从此处和其他.then()处将其删除,那么它也应该可以工作