How to get response data outside promise chain of Fetch? [duplicate]

十年热恋 提交于 2019-12-13 12:48:08

问题


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:


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);
    });


来源:https://stackoverflow.com/questions/41263986/how-to-get-response-data-outside-promise-chain-of-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!