Skip to content Skip to sidebar Skip to footer

How To Return Nested Promise

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

Solution 1:

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 promisereturn sql.connect(config.properties).then(result => {
    let request = new sql.Request();
    // chain this promise onto prior promisereturn request.query("SELECT " + columnName + " FROM " + table);
  });
} // getColumn('username', 'Login').then(val => {
   console.log(val);
}).catch(err => {
   console.log(err);
});

Post a Comment for "How To Return Nested Promise"