[英]console.log doesn't wait "await" in async function
我有這個代碼
async function dataget(APIURL){
let x = false;
let xhr = new XMLHttpRequest();
xhr.open("GET", APIURL);
xhr.send();
xhr.onload = await function(){
if(1 == 1){
x = true
}else{
x = "gg"
}
}
console.log(x)
}
console.log(dataget("data.json"));
我希望控制台等到加載 function 結束(當 x = true 時),但這不會發生,控制台返回 false 並且不等待
這是 output:
我想要一個解釋而不僅僅是解決方案
您需要打開dataget
以返回promise
,它將在執行onload
function 后解決,因此您可以等待它並return
結果。
function dataget(APIURL){
return new Promise((resolve, reject) => {
let x = false;
let xhr = new XMLHttpRequest();
xhr.open("GET", APIURL);
xhr.send();
xhr.onload = function(){
if(1 == 1){
resolve(x = true)
}else{
resolve(x = "gg")
}
}
})
}
(async () => {
const result = await dataget("data.json")
console.log(result);
})()
這是使代碼執行您想要的操作的一種方法
async function dataget(APIURL) {
const x = await new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open("GET", APIURL);
xhr.send();
xhr.onload = () => {
if (1 == 1) {
resolve(true);
} else {
resolve("gg");
}
};
});
console.log(x);
return x;
}
console.log(dataget("data.json"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.