Last active
April 6, 2020 17:46
-
-
Save pedroalmeida415/2d2c20eb8adb0db75ac21d44cd9902cf to your computer and use it in GitHub Desktop.
Make 2 or more fully parallel asynchronous requests, handle individual errors and do something if they all succeed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const multipleConcurrentRequests = async (...parameters) => { | |
// This only works with Async/Await syntax, so it has to be inside an Async function | |
// Start 2 "jobs" in parallel and wait for both of them to complete | |
await Promise.all([ | |
(async () => | |
await axios.post("request.url", { | |
someData: dataValue, | |
}))().catch((error) => { | |
// Handle this request's error... | |
console.log(error); | |
throw error; // You have to throw the error as well, otherwise the Promise.all will resolve even | |
// with this request not being successful | |
}), | |
(async () => await axios.get("request.url"))().catch((error) => { | |
// Handle this request's error... | |
console.log(error); | |
throw error; // You have to throw the error as well, otherwise the Promise.all will resolve even | |
// with this request not being successful | |
}), | |
// You can add as many blocks of 'jobs' like the ones above as you want | |
]).then((...responses) => { | |
//Do something when they all complete, using their responses or not | |
const response1 = responses[0]; | |
const response2 = responses[1]; | |
// ... | |
console.log(response1); | |
console.log(response2); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment