Reputation: 103
I'm using request-promise-native
module on node.js. The API I'm calling returns the required data via a 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. 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). This is visible in the ... console.log(response) ... but not in the variable usdToEosMul.
Upvotes: 0
Views: 6862
Reputation: 665316
the function which because it is preceded with
async
returns a 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)
}
Upvotes: 2