在Promise.all中使用Fetch API [英] Using Fetch API with Promise.all
本文介绍了在Promise.all中使用Fetch API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目标是从两个URL获取数据,并仅在两者成功返回时执行操作。另一方面,如果其中任何一个失败,我想返回一个错误。我玩过我的代码并设法获得预期的效果。
my aim is to fetch data from two URLs and perform an action only when both have come back successfully. On the other hand i want to return an error if either of them fail. I have played around with my code and managed to get the desired effect.
我的问题是,是否有更有效,简洁的方法来实现相同的功能?
My question is, is there a more efficient, succinct way of achieving the same functionality?
助手功能
let status = (r) => {
if (r.ok) {
return Promise.resolve(r)
} else {
return Promise.reject(new Error(r.statusText))
}
}
let json = (r) => r.json();
请求
let urls = [
'http://localhost:3000/incomplete',
'http://localhost:3000/complete'
]
let promises = urls.map(url => {
return fetch(url)
.then(status)
.then(json)
.then(d => Promise.resolve(d))
.catch(e => Promise.reject(new Error(e)));
});
Promise.all(promises).then(d => {
// do stuff with d
}).catch(e => {
console.log('Whoops something went wrong!', e);
});
推荐答案
使用 fetchOk 以获取更好的错误消息,并 destructuring 访问结果:
let fetchOk = (...args) => fetch(...args)
.then(res => res.ok ? res : res.json().then(data => {
throw Object.assign(new Error(data.error_message), {name: res.statusText});
}));
Promise.all([
'http://localhost:3000/incomplete',
'http://localhost:3000/complete'
].map(url => fetchOk(url).then(r => r.json()))).then(([d1, d2]) => {
// do stuff with d1 and d2
}).catch(e => console.error(e));
// Work around stackoverflow's broken error logger.
var console = { error: msg => div.innerHTML += msg + "<br>" };
<div id="div" style="white-space: pre;"></div>
这篇关于在Promise.all中使用Fetch API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文