我想在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”,而不是我期望返回的对象数组。当我进行一次读取并使用数据变量时,没有问题。但是,我对于如何从对多个端点的调用中访问返回的数据感到困惑。我在这里尝试了所有解决方案,都在获取api,但是没有一个有效。如果有人能阐明从提取中访问数据的正确方法,我将非常感激。
你就在那里。问题是您的第一个then
返回了一个promise数组。不幸的是,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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句