我正在尝试使用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
语句进行比较?
您已将三个独立的函数参数定义为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
})
}
如果您想保留范围,也许更好的方法是将其写为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的原因是因为:
sql.connect(config.properties).then((pool, req) => {
您期望由于.then()
(这是一个带阴影的变量)的结果而将要求传递给您。如果您从此处以及其他.then()
中删除它,那么它也应该可以工作