简体   繁体   中英

API call leads to pending promise

I am attempting to store an API call response into the variable cat . When I execute the following code, the console logs Promise { <pending> } . Why is this occuring?

const got = require('got');

let dog = async () => {
    try {
        const response = await got('https://api.coinpaprika.com/v1/coins/btc-bitcoin');
        return response;
    } catch (error) {
        console.log(error.response.body);
        //=> 'Internal server error ...'
    }
}

let cat = dog();
console.log(cat)

dog() will return a promise because it is an async function. You can get the value like that:

let cat = await dog();

OR

dog().then((cat)=>{
  // do something here with the response
})
const got = require('got');

let dog = async () => {
    try {
        const response = await got('https://api.coinpaprika.com/v1/coins/btc-bitcoin');
        return await response.json();
    } catch (error) {
        console.log(error.response.body);
        //=> 'Internal server error ...'
    }
}

let cat = dog();
console.log(cat)

In your code, response is a promise. I expect your price data is being returned as JSON so you need to add return await response.json() which will instead return a JSON object you can print out to the console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM