I'm using fetchApi to get data from my API. In my RequestHelpers.js, I do this code
module.exports = {
fetchQuizCollection(){
return fetch(HOST+API_KEY)
.then((response) => response.json())
.then((responseData) => {
let gameData = responseData
console.log(responseData) //It work
return responseData
})
.done();
}
}
And I call that function in another file, I couldn't get my responseData
let sampleQuiz = RequestHelpers.fetchQuizCollection()
console.log(sampleQuiz) //undefined
is there any way to get data outside the promise ?
You are treating asynchronous code as if it's synchronous. The
fetchQuizCollection()
is asynchronous, thus the data it returns isn't available when your logging code runs. You will have to wait until all the.fetch()
functions have completed.Just let
fetchQuizCollection()
return a promise by adding anotherreturn
as belowand you can access the
sampleQuiz
in a.then()
function.