In the first example, I fetch data using ajax
using XMLHttpRequest
and it works fine
example 1
let req = new XMLHttpRequest();
req.open(
"GET",
"https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-temperature.json"
);
let res = {};
req.onload = () => {
res = JSON.parse(req.responseText);
};
req.send();
window.onload = _ => {
console.log(res);
};
but i want to use the async
function to save and minimize my code in single function
and here it is what i try
example 2
async function res() {
let req = new XMLHttpRequest();
req.open(
"GET",
"https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-temperature.json"
);
let res = {};
req.onload = () => {
res = JSON.parse(req.responseText);
};
req.send();
return await res;
}
window.onload = _ => {
console.log(res());
};
but it log
in the console
every time
Promise {<pending>}