I have this code
JavaScript
x
16
16
1
async function dataget(APIURL){
2
let x = false;
3
let xhr = new XMLHttpRequest();
4
xhr.open("GET", APIURL);
5
xhr.send();
6
xhr.onload = await function(){
7
if(1 == 1){
8
x = true
9
}else{
10
x = "gg"
11
}
12
}
13
console.log(x)
14
}
15
console.log(dataget("data.json"));
16
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:
I want an explanation not just the solve
Advertisement
Answer
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.
JavaScript
1
22
22
1
function dataget(APIURL){
2
return new Promise((resolve, reject) => {
3
let x = false;
4
let xhr = new XMLHttpRequest();
5
xhr.open("GET", APIURL);
6
xhr.send();
7
xhr.onload = function(){
8
if(1 == 1){
9
resolve(true)
10
}else{
11
resolve("gg")
12
}
13
}
14
})
15
}
16
17
(async () => {
18
const result = await dataget("data.json")
19
console.log(result); // true
20
})()
21
22