使用Vue中的抓取功能一次制作多个api请求

问题描述 投票:1回答:1

我想在我的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”,而不是我期望返回的对象数组。当我执行一次读取并使用数据变量时,没有问题。但是我对于如何访问从多个端点的提取调用中返回的数据感到困惑。我在这里fetching api's尝试了所有解决方案,但没有一个有效。如果有人能阐明从提取中访问数据的正确方法,我将非常感激。

vue.js fetch es6-promise
1个回答
1
投票

你就在那里。问题是您的第一个then返回promise array。不幸的是,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

© www.soinside.com 2019 - 2024. All rights reserved.