Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 onload function ends (when x = true), but this doesn’t happen,
console returns false and doesn’t wait

this is the output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

I want an explanation not just the solve

>Solution :

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
})()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading