Reputation: 1581
I am trying to return the result
parameter from the getColumn
function. When logging, it returns undefined.
The connection function connects to a SQL DB and the query returns a data set.
How can I pass the variable back up the promise chain?
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'))
Upvotes: 4
Views: 7791
Reputation: 708146
First off, you can't return a value directly form getColumn()
. The insides of that function are asynchronous so the value won't be known until AFTER getColumn()
returns. You are currently getting undefined
from getColumn()
because it has no return value. The return
you do have is to an asynchronous .then()
handler, not for getColumn()
. There is no way to return the final value from getColumn()
. It's asynchronous. You have to either return a promise or use a callback. Since you're already using promises internal to the function, you should just return a promise.
You can return a promise from getColumn()
and use .then()
or await
with that promise to get the value.
To return a promise, you need to return the internal promises:
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);
});
Upvotes: 8