繁体   English   中英

在异步/等待功能完成之前执行代码?

[英]Code executing before async/await function finishes?

我是异步编程的新手,我试图了解ES6的异步/等待。 我有以下代码:

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)

您的问题是您正在混合异步代码和同步代码。 您将需要await或者then您要等待的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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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