【问题标题】:Code executing before async/await function finishes?在 async/await 函数完成之前执行的代码?
【发布时间】:2018-05-27 21:09:48
【问题描述】:

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

【问题讨论】:

  • 你没有。这不是这样的。将 console.log 移动到一个回调中,一旦工作完成就会被调用。异步函数仍然是异步的。您仍然需要等待它完成。
  • 异步代码的全部意义在于它不等待。如果您想在 request 完成后进行日志记录,请通过 .then 链接您的日志记录代码,就像其他 lambdas 一样。
  • 一个函数只有在使用await关键字调用时才会等待函数完成。 await 关键字只能在 async 函数内使用。因此,您不能await 让函数在全局(最顶层)范围内完成。

标签: javascript asynchronous ecmascript-6 promise fetch


【解决方案1】:

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

【讨论】:

  • 您可能希望在main 中使用await 而不是then
  • @Bergi 好电话。
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 2018-12-15
  • 2019-02-22
  • 2021-03-31
  • 1970-01-01
相关资源
最近更新 更多