我的目标是从两个 URL 获取数据,并仅在两个 URL 均成功返回时才执行操作。另一方面,如果其中任何一个失败,我想返回错误。我已经尝试了我的代码并设法获得了预期的效果。
我的问题是,是否有更有效、更简洁的方法来实现相同的功能?
辅助函数
let status = (r) => {
if (r.ok) {
return Promise.resolve(r)
} else {
return Promise.reject(new Error(r.statusText))
}
}
let json = (r) => r.json();
Run Code Online (Sandbox Code Playgroud)
要求
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);
});
Run Code Online (Sandbox Code Playgroud)