[英]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. 如果这样做,还可以将
then
和catch
方法重写为更简单的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.