1
votes

I'm using async/await to make a query to database and get the result, but I don't know why I've got this error in browser console:

Unhandled promise rejection TypeError: "games is undefined"

I've got two functions, getData which is async and make a call to getGames:

getGames(){
    let query = HOMELF1_NEXT_GAMES;
    var data = {
        "query": query,
        "variables": null
    }
    fetch(URL_FEB_API, {
        method: "POST",
        headers: {
            "Accept"        :   "application/json",
            "content-type"  :   "application/json"
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        return response.json()
    })
    .then(data => {
        console.log("End query");
        return data;
    })
    .catch(err => {
        console.log("Error: " + err)
    })
}

async getData(){
    console.log("Before getGames");
    let games = await this.getGames();
    console.log("After getGames");
    console.log("games: " + games.length)
}

componentDidMount(){
    this.getData();
};

And in browser console I've got this result:

enter image description here

Why is not working here async/await? What am I doing wrong?

1
getGames() does not return anythingThomas
getGames() is undefined because the function doesn't return anything. All you need to do to fix this is put a return right before your fetch.Chris G
return promise .i.e. in this case it is fetchHarish
It works!!! Thanks to @Thomas for your apreaciated help!!!José Carlos
It works!!! Thanks to @Chris G for your apreciated help!!!José Carlos

1 Answers

1
votes

You just forgot the return

getGames(){
    let query = HOMELF1_NEXT_GAMES;
    var data = {
        "query": query,
        "variables": null
    }
     \/ here
    return fetch(URL_FEB_API, {
        method: "POST",
        headers: {
            "Accept"        :   "application/json",
            "content-type"  :   "application/json"
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        return response.json()
    })
    .then(data => {
        console.log("End query");
        return data;
    })
    .catch(err => {
        console.log("Error: " + err)
    })
}

async getData(){
    console.log("Before getGames");
    let games = await this.getGames();
    console.log("After getGames");
    console.log("games: " + games.length)
}

componentDidMount(){
    this.getData();
};