Return 来自 promise 使用函数的数据

Return data from promise using function

我在 javascript 中创建函数以从数据库中获取数据 我 return 结果,但没有给我预期的结果

函数

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

输出

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

预期输出

City, Address, Price

由于您正在使用 promises,因此 return 您的结果的方法是使用 then 解决它。您还可以使用 catch 处理错误。在你的情况下,它看起来像这样

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

你可以使用 async, await 来简化 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;
    }

};