简体   繁体   English

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

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

I'm new to asynchronous programming and I'm trying to understand async/await with ES6. 我是异步编程的新手,我试图了解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. 据我了解, request()函数应在进入下一行之前执行,但显然不能以这种方式工作。

What do I need to do to get the code to wait until request() has finished before performing the console.log(user) ? 我需要怎么做才能让代码等到request()完成之后再执行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. 您将需要await或者then您要等待的request呼叫。

One option would be to move your code into an async function and then call it. 一种选择是将您的代码移入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();

If you do this, you can also rewrite your then and catch methods into a simpler try/catch statement. 如果这样做,还可以将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.

相关问题 函数在等待完成之前返回 - Function returns before await finishes executing 停止执行代码,直到我的 async/await HttpClient get 操作完成执行代码(包括 html 调用) - Stop executing code until my async/await HttpClient get operation finishes executing code (including html calls) 在等待完成之前正在调用 Function - Function is being called before await finishes await 函数在进入下一行之前没有执行。 (异步/等待不起作用) - await function is not executing before going on next line. (Async/await not working) 在异步函数完成运行之前反应渲染 - React rendering before async function finishes running 异步等待函数未在事件侦听器中执行 - Async await function not executing within an event listener map function 中的异步等待未按顺序执行 - Async await in map function not executing in order Vue.js异步/等待,然后函数不执行 - Vue.js async/await with then function not executing 为什么在稍后启动 promise 之后异步 function 完成执行? - Why does an async function finishes executing after a promise started later? 在另一个异步 function 中执行代码之前,如何在异步 function 中等待循环完成? - How to wait for a loop to finish in an async function before executing code in another async function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM