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?
Helper functions
let status = (r) => {
if (r.ok) {
return Promise.resolve(r)
} else {
return Promise.reject(new Error(r.statusText))
}
}
let json = (r) => r.json();
Requests
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);
});