如何在Fetch承诺链之外获取响应数据? [英] How to get response data outside promise chain of Fetch?

查看:154
本文介绍了如何在Fetch承诺链之外获取响应数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fetchApi从我的API中获取数据。
在我的RequestHelpers.js中,我执行以下代码

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

然后我在另一个文件中调用该函数,没得到我的responseData

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 ?

推荐答案

您正在将异步代码视为同步代码。 fetchQuizCollection()是异步的,因此在您的日志记录代码运行时,返回的数据不可用。您将必须等到所有 .fetch()函数都已完成。

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.

只需让 fetchQuizCollection()通过添加另一个返回来返回承诺,如下所示

Just let fetchQuizCollection() return a promise by adding another return as below

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

,您可以在以下位置访问 sampleQuiz .then()函数。

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

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

这篇关于如何在Fetch承诺链之外获取响应数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆