1

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>}
Joseph
  • 5,644
  • 3
  • 18
  • 44
  • You are awaiting `res` variable which is an empty object. – norbitrial Jan 02 '20 at 13:57
  • but i try to get its value from this part `req.onload = () => { res = JSON.parse(req.responseText); };` – Joseph Jan 02 '20 at 14:00
  • Or more simply put `res().then(response => { console.log(response) }).catch(() => { alert("bad stuff"); })` – BRO_THOM Jan 02 '20 at 14:20
  • @BRO_THOM it print empty object – Joseph Jan 02 '20 at 14:27
  • My bad, I thought I saw you using `Fetch` in the second snippet, but you're still using an `XMLHttpRequest` - you need to put your code within the `req.onload` function, because `onload` is the code that is executed after your request has been completed. – BRO_THOM Jan 02 '20 at 14:29
  • did you mean like that `req.onload = async () => { let res = JSON.parse(req.responseText); req.send(); return await res; };` ? – Joseph Jan 02 '20 at 14:33

2 Answers2

1

To use async function you have to return the Promise

You could use the fetch function as well it's a more modern way to fetching data.

Example:

const httpRequest = async () => {
    try {
        const response = await fetch('http://example.com/movies.json');
        return await response.json();
    } catch(e) {
        console.err(e);
    }
}

To solve your problem try to use so:

function request() {
    return new Promise((resolve, reject) => {
        let req = new XMLHttpRequest();

        req.open(
            "GET",
            "https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-temperature.json"
        );

        req.onload = () => {
            resolve(JSON.parse(req.responseText));
        };

        req.send();
    })
}

function res() {
    request().then(data => console.log(data));
}

window.onload = _ => {
    console.log(res());
};
0

You are awaiting res variable which is an empty object. Try to await the Promise. Example:

await req
return res

If that doesn't work try .then()