【问题标题】:Making multiple api requests at once using fetch in vue在 vue 中使用 fetch 一次发出多个 api 请求
【发布时间】:2020-08-10 10:15:53
【问题描述】:

我想一次对我的 vue 组件中的一个 ReST API 进行两个 api 调用。我在网上做过研究,正在使用这个逻辑:

// Multiple fetches
      Promise.all([
        fetch(
          `https://api.covid19api.com/live/country/${this.selected}/status/confirmed/date/${this.yesterday}`
        ),
        fetch(
          `https://api.covid19api.com/live/country/south-africa/status/confirmed/date/2020-03-21T13:13:30Z`
        )
      ])
        .then(responses => {
          // Get a JSON object from each of the responses
          return responses.map(response => {
            return response.json();
          });
        })
        .then(data => {
          // Log the data to the console
          // You would do something with both sets of data here

          this.coronaVirusStats1 = data[0];
          console.log(this.coronaVirusStats1);
        })
        .catch(function(error) {
          // if there's an error, log it
          console.log(error);
        });
    }

控制台值是我理解的承诺,但是当我查看组件下的 Vue devTools 时,我发现 coronaVirusStats1 的值是“Promise”,而不是我期望返回的对象数组。当我进行一次提取并使用数据变量时,没有问题。但是,我对如何访问从对多个端点的 fetch 调用返回的数据感到困惑。我在这里尝试了所有解决方案fetching api's,但没有一个奏效。如果有人能阐明从提取中访问数据的正确方法,我将不胜感激。

【问题讨论】:

    标签: vue.js fetch es6-promise


    【解决方案1】:

    你就在那里。问题是您的第一个then 返回一个承诺数组。不幸的是,promise 链仅适用于 Promise 实例,因此这里没有任何东西可以等待您的 Promise 解决。

    快速解决方法是将第一个 then 更改为

    return Promise.all(responses.map(r => r.json()))
    

    话虽如此,fetch API 还有更多功能,尤其是在处理错误方面。

    我会为每个 fetch 调用使用类似以下的内容,以确保正确处理网络错误和不成功的 HTTP 请求。

    这还将处理解包 JSON 响应,因此您不必使用上述方法

    Promise.all([
      fetch(url1).then(res => res.ok && res.json() || Promise.reject(res)),
      fetch(url2).then(res => res.ok && res.json() || Promise.reject(res))
    ]).then(data => {
      // handle data array here
    })
    

    https://developer.mozilla.org/en-US/docs/Web/API/Response/ok

    【讨论】:

    • 感谢您对问题的简明扼要的解释。就在我认为我得到了承诺时,另一个用例让我陷入了循环。我认为第一个 .then 会等待所有响应通过 .json(),然后一组数据将传递给第二个 .then。 Promise 和这确实是 JavaScript 开发人员的烦恼:) 我想知道我从谷歌搜索中看到的所有示例如何从未解决多个获取请求的这一方面。保持安全。
    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多