[英]Code executing before async/await function finishes?
我是異步編程的新手,我試圖了解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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.