简体   繁体   中英

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

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));

You can use async, await to simplify the promise.

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

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM