简体   繁体   中英

Why does my async function always return a pending promise?

When I console.log(data), I log the information I need, but if return the value of data in getWeather(), it just returns a pending promise. I have tried many things, but none have worked so far. I'll leave my broken code below.

const axios = require('axios');
const getWeather = async () => {
    try {
        let response = await axios.get(
            'http://api.openweathermap.org/data/2.5/forecast?id=524901&appid={apiKey}'
        );

        let data = response.data;
        return data;
    } catch (e) {
        console.log(e);
    }
};

async function returnAsync() {
    const x = await getWeather();
    return x;
}
console.log(getWeather()); // returns a pending promise
console.log('check ', returnAsync()); // also returns a pending promise

async functions must return a promise. (they implicitly return Promise<void> instead of void !)

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

For example, the following:

 async function foo() { return 1 }

...is equivalent to:

 function foo() { return Promise.resolve(1) }

Source

//const getWeather = async () => {...

An async function's return value will be a Promise which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function.

check more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

This could be to do with the fact that you're trying to call an async function inside of a synchronous function. It's quite a common mistake to make, so don't fret. Typically if you think about the structure, the console logs could technically be run before the async function has completed. That's why we have "callback functions" which basically just run as soon as the async returns a value.

Axios has a really neat way to use these callbacks which is just using the .then() function.

So try this out and see if it works:

const axios = require('axios');
const getWeather = async () => {
    axios.get('http://api.openweathermap.org/data/2.5/forecast?id=524901&appid={apiKey}')
    .then(json => console.log(json))
    .catch(error => console.log(error))
};

getWeather();

Because you're trying to call the get request inside of an async function, you cannot then grab the data in a synchronous function.

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