How to get response data outside promise chain of Fetch?

3.8k views Asked by At

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 ?

1

There are 1 answers

0
Daniel B On

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 another return as below

return fetchQuizCollection(){
  return fetch(HOST+API_KEY)
    .then((response) => response.json())
    ...

and you can access the sampleQuiz in a .then() function.

let sampleQuiz = RequestHelpers.fetchQuizCollection()
    .then((sampleQuiz) => {
        console.log(sampleQuiz);
    });