繁体   English   中英

console.log 不会在异步 function 中等待“等待”

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM