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:
Why is not working here async/await? What am I doing wrong?
getGames()
does notreturn
anything – ThomasgetGames()
isundefined
because the function doesn't return anything. All you need to do to fix this is put areturn
right before yourfetch
. – Chris Gpromise
.i.e. in this case it isfetch
– Harish