When fetching data in the first example using ajax
with XMLHttpRequest
, everything works smoothly.
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);
};
However, I wanted to streamline and condense my code using the async
function. Here is what I attempted:
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());
};
Unfortunately, it consistently logs the following in the console:
Promise {<pending>}