在async / await函数完成之前执行代码?

时间:2017-12-13 21:09:57

标签: javascript asynchronous ecmascript-6 promise fetch

我是异步编程的新手,我试图理解与ES6的async / await。我有以下代码:

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);

我的问题是控制台日志在数据完成提取之前发生,因此我得到以下结果:

[]
fetching: 255.277ms

我理解的方法是在进入下一行之前应该执行request()函数,但它显然不会以这种方式工作。

在执行request()之前,我需要做些什么才能让代码等到console.log(user)完成?

1 个答案:

答案 0 :(得分:2)

您的问题是您正在混合异步和同步代码。您需要awaitthen要等待的request电话。

一种选择是将代码移到async函数中,然后调用它。

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();

如果这样做,您还可以将thencatch方法重写为更简单的try / catch语句。

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();