使用函数从promise返回数据

编程入门 行业动态 更新时间:2024-10-06 04:12:08

使用<a href=https://www.elefans.com/category/jswz/34/1771370.html style=函数从promise返回数据"/>

使用函数从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返回数据

本文发布于:2024-05-06 17:05:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1753582.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   数据   promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!