我是异步编程的新手,我试图理解与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)
完成?
答案 0 :(得分:2)
您的问题是您正在混合异步和同步代码。您需要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();
如果这样做,您还可以将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();