我是异步编程的新手,我正在尝试了解 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)
?
最佳答案
您的问题是您混合了异步和同步代码。您需要 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();
关于javascript - 在异步/等待函数完成之前执行的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47802153/