函数从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返回数据
发布评论