我正在尝试result
从getColumn
函数返回参数。记录时,它返回未定义。
连接功能连接到SQL DB,查询返回一个数据集。
如何将变量传递回诺言链?
getColumn = function(columnName, table) {
sql.connect(config.properties)
.then(result => {
let request = new sql.Request();
request.query("SELECT " + columnName + " FROM " + table)
.then(result => {
// want to return this result from the getColumn function
return result
}).catch(err => {
// Query error checks
})
}).catch(err => {
// Connection error checks
})
} //
console.log(getColumn('username', 'Login'))
首先,您不能直接从form返回值getColumn()
。该函数的内部是异步的,因此只有在AFTERgetColumn()
返回之前,该值才是已知的。您正在undefined
从中获取信息,getColumn()
因为它没有返回值。该return
你做的已经是一个异步.then()
处理,而不是getColumn()
。无法从中返回最终值getColumn()
。它是异步的。您必须返回一个Promise或使用回调。由于您已经在使用函数内部的promise,因此应该只返回promise。
您可以返回一个承诺getColumn()
并与之一起使用.then()
或await
与该承诺一起获得价值。
要返回承诺,您需要返回内部承诺:
const getColumn = function(columnName, table) {
// return promise
return sql.connect(config.properties).then(result => {
let request = new sql.Request();
// chain this promise onto prior promise
return request.query("SELECT " + columnName + " FROM " + table);
});
} //
getColumn('username', 'Login').then(val => {
console.log(val);
}).catch(err => {
console.log(err);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句