Search code examples
javascriptnode.jssql-serverpromisees6-promise

Return data from promise using function


i am created function in javascript to fetch the data from database and i return the result but it not give me expected result

Function

const getData = id => {
  return new sql.ConnectionPool(config).connect().then(pool => {
    return pool
      .request()
      .query(`select City,Address,Price from Temp where tempId='${id}'`)
      .then(result => {
        sql.close();
        return result;
      })
      .catch(e => {
        sql.close();
      });
  });
};

Output

Promise {
    _bitField: 0,
    _fulfillmentHandler0: undefined,
    _rejectionHandler0: undefined,
    _promise0: undefined,
    _receiver0: undefined 
} 

Expected Output

City, Address, Price


Solution

  • Since you're working with promises, the way to return your result is to resolve it using then. You can also handle errors using catch. In your case it will look like this

    // Your function that returns a promise
    const getData = id => {
      return new sql.ConnectionPool(config).connect().then(pool => {
        return pool
          .request()
          .query(`select City,Address,Price from Temp where tempId='${id}'`)
          .then(result => {
            sql.close();
            return result;
          })
          .catch(e => {
            sql.close();
          });
      });
    };
    
    // How you actually get the result
    getData('yourIdGoesHere')
        .then(data => {
            // Your data is here
            console.log(data);
        }).catch(err => console.error(err));