简体   繁体   中英

Code executing before async/await function finishes?

I'm new to asynchronous programming and I'm trying to understand async/await with ES6. I have the following code:

import "isomorphic-fetch";

const url = "https://randomuser.me/api/";
const user = [];

console.time('fetching');
const request = async() => {
    const data = await fetch(url);
    const json = await data.json();
    return json;
}
request()
    .then(data => console.timeEnd('fetching'))
    .then(data => user.push(data))
    .catch(error => console.log("There was an error fetching the data: \n", error));

request();
console.log(user);

My problem is that the console log happens before the data has finished being fetched, so I get the following result:

[]
fetching: 255.277ms

The way I understand it is that the request() function should be performed before moving on to the following line, but it doesn't apparently work this way.

What do I need to do to get the code to wait until request() has finished before performing the console.log(user) ?

Your issue is that you are mixing asynchronous and synchronous code. You would need to await or then the request call you want to wait for.

One option would be to move your code into an async function and then call it.

import "isomorphic-fetch";

const url = "https://randomuser.me/api/";
const user = [];

console.time('fetching');
const request = async() => {
    const data = await fetch(url);
    const json = await data.json();
    return json;
}

async function main() {
    await request()
        .then(data => console.timeEnd('fetching'))
        .then(data => user.push(data))
        .catch(error => console.log("There was an error fetching the data: \n", error));

    console.log(user);
}
main();

If you do this, you can also rewrite your then and catch methods into a simpler try/catch statement.

import "isomorphic-fetch";

const url = "https://randomuser.me/api/";
const user = [];

console.time('fetching');
const request = async() => {
    const data = await fetch(url);
    const json = await data.json();
    return json;
}

async function main() {
    try {
        const data = await request();
        console.timeEnd('fetching');
        user.push(data);
    }
    catch (err) {
        console.log("There was an error fetching the data: \n", error)
    }

    console.log(user);
}
main();

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