最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

使用函数从promise返回数据

IT培训 admin 9浏览 0评论

使用函数从promise返回数据

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

功能

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 
} 

预期产出

城市,地址,价格

回答如下:

由于您正在使用promises,因此返回结果的方法是使用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));

使用函数从promise返回数据

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

功能

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 
} 

预期产出

城市,地址,价格

回答如下:

由于您正在使用promises,因此返回结果的方法是使用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));

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论