Home > Blockchain >  console.log doesn't wait "await" in async function
console.log doesn't wait "await" in async function

Time:09-20

I have this code

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"));

I want console to wait until onl oad function ends (when x = true), but this doesn't happen, console returns false and doesn't wait

this is the output:

enter image description here

I want an explanation not just the solve

CodePudding user response:

You need to turn the dataget function to return a promise which will resolve after the onload function executed, so you can await it and return the result.

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(true)
        }else{
            resolve("gg")
        }
      }
    })
}

(async () => {
  const result = await dataget("data.json") 
  console.log(result); // true
})()

CodePudding user response:

Here's one way to make the code do what you want

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;
}
(async () => {
  console.log(await dataget("data.json"));
})();
  • Related