0

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:

enter image description here

I want an explanation not just the solve

HamzaElkotb
  • 138
  • 1
  • 7
  • 2
    You're awaiting a function expression, which immediately resolves to... the function. – jonrsharpe Sep 20 '22 at 10:38
  • that's not how you promisify XMLHttpRequest ... also, why would console.log await if you don't have the word `await`? – Jaromanda X Sep 20 '22 at 10:39
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ivar Sep 20 '22 at 10:41
  • @Jaromanda X I used "return" in first but now I use console to make it clear – HamzaElkotb Sep 20 '22 at 10:41
  • Does this answer your question? [How do I promisify native XHR?](https://stackoverflow.com/questions/30008114/how-do-i-promisify-native-xhr) – mani Sep 20 '22 at 10:43
  • @HamzaElkotb - what? that makes no sense – Jaromanda X Sep 20 '22 at 10:43

2 Answers2

1

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

Mina
  • 14,386
  • 3
  • 13
  • 26
1

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"));
})();
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87