I have successfully implemented a functionality that fetches data from two URLs and performs an action only when both requests are successful. However, I am curious if there is a more efficient and succinct way to achieve the same result.
Helper functions
let checkStatus = (response) => {
if (response.ok) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
let parseJson = (response) => response.json();
Requests
let urls = [
'http://localhost:3000/incomplete',
'http://localhost:3000/complete'
]
let promises = urls.map(url => {
return fetch(url)
.then(checkStatus)
.then(parseJson)
.then(data => Promise.resolve(data))
.catch(error => Promise.reject(new Error(error)));
});
Promise.all(promises).then(data => {
// Perform actions with the data
}).catch(error => {
console.log('Oops, something went wrong!', error);
});