[英]How to get a promise to resolve naturally with request-promise-native
I'm using request-promise-native
module on node.js. 我在node.js上使用request-promise-native
模块。 The API I'm calling returns the required data via a GET. 我正在调用的API通过GET返回所需的数据。 That works just fine. 那很好。
However, when I try to get the data from the function which because it is preceded with Async returns a promise, I just can't get the syntax right. 但是,当我尝试从该函数中获取数据时,由于该数据前面带有Async会返回一个Promise,因此我只是无法正确获取语法。 Here's what I've tried: 这是我尝试过的:
const request = require('request-promise-native');
async function usdToEos () {
const options = {
method: 'GET'
,uri: 'https://api.coincap.io/v2/assets/eos'
,json: true
}
const response = await request(options)
.then(response => {
console.log(response)
return (1 / response.data.priceUsd)
})
.catch(error => {
console.log('\nCaught exception: ' + error);
})
}
var usdToEosMul = usdToEos()
console.log('\n' + 'USD multiplier to convert to EOS' + '\n')
console.log(usdToEosMul)
How do I get the returned value to be ... the data ... (1 / response.data.priceUsd). 我如何获得返回值是...数据...(1 / response.data.priceUsd)。 This is visible in the ... console.log(response) ... but not in the variable usdToEosMul. 这在... console.log(response)...中可见,但在变量usdToEosMul中则看不到。
the function which because it is preceded with
async
returns a promise 由于其前面带有async
功能的函数返回一个promise
Seems like you nearly answered your question already. 似乎您已经差不多回答了您的问题。 You will have to wait for that promise at your call site: 您将不得不在呼叫站点上等待该承诺:
usdToEos().then(usdToEosMul => {
console.log('\n' + 'USD multiplier to convert to EOS' + '\n')
console.log(usdToEosMul)
}).catch(error => {
console.log('\nCaught exception: ' + error)
})
function usdToEos() {
const options = {
method: 'GET'
,uri: 'https://api.coincap.io/v2/assets/eos'
,json: true
}
return request(options).then(response => {
console.log(response)
return (1 / response.data.priceUsd)
})
}
or 要么
;(async function() {
try {
const usdToEosMul = await usdToEos()
console.log('\n' + 'USD multiplier to convert to EOS' + '\n')
console.log(usdToEosMul)
} catch(error) {
console.log('\nCaught exception: ' + error)
}
}())
async function usdToEos() {
const options = {
method: 'GET'
,uri: 'https://api.coincap.io/v2/assets/eos'
,json: true
}
const response = await request(options)
console.log(response)
return (1 / response.data.priceUsd)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.