javascript - 在异步/等待函数完成之前执行的代码?

标签 javascript asynchronous ecmascript-6 promise fetch

我是异步编程的新手,我正在尝试了解 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)

最佳答案

您的问题是您混合了异步和同步代码。您需要 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();

关于javascript - 在异步/等待函数完成之前执行的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47802153/

相关文章:

javascript - 自定义迭代器返回空数组

javascript - 在既不是 React 函数组件也不是自定义 React Hook 函数的函数中调用 React Hook

javascript - 为什么 Javascript 从字符串中删除前导零?

python - 在python中异步读取和处理图像

asynchronous - 如何在 Rust Hyper 中将响应主体读取为字符串?

javascript - 如何从异步调用返回响应?

javascript - 将 Fetch API 与 Promise.all 结合使用

javascript - 支持旧浏览器与 terser + rollup 吗?

javascript - window.opener 返回 null

javascript - 如何从此日志输出中找到最里面的失败模式