Forked from munkacsitomi/promise-all-error-handling.js
Created
August 11, 2022 05:16
-
-
Save antonga23/474cd87a647039795b4db2e043dbb005 to your computer and use it in GitHub Desktop.
Promise.all error handling
This file contains 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 pause = (data, time) => new Promise(resolve => setTimeout(() => resolve(data), time)); | |
const pauseReject = (data, time) => | |
new Promise((resolve, reject) => | |
setTimeout(() => reject(new Error(`Something went wrong in the ${data} promise`)), time) | |
); | |
const parallelErrorHandlingWrong = () => { | |
const firstPromise = pause('first', 3000); | |
const secondPromise = pauseReject('second', 2000); | |
const thirdPromise = pause('third', 1000); | |
// Promise.all is all or nothing, it either resolves with an array of all resolved values, or rejects with a single error | |
Promise.all([firstPromise, secondPromise, thirdPromise]) | |
.then(([first, second, third]) => console.log('parallelErrorHandlingWrong:', first, second, third)) | |
.catch(err => console.log(err)); | |
}; | |
const parallelErrorHandlingOneByOne = () => { | |
// we can handle errors one by one | |
const firstPromise = pause('first', 3000).catch(err => console.log(err)); | |
const secondPromise = pauseReject('second', 2000).catch(err => console.log(err)); | |
const thirdPromise = pause('third', 1000).catch(err => console.log(err)); | |
Promise.all([firstPromise, secondPromise, thirdPromise]) | |
.then(([first, second, third]) => console.log('parallelErrorHandlingOneByOne:', first, second, third)); | |
}; | |
const parallelErrorHandlingTogether = () => { | |
const firstPromise = pause('first', 3000); | |
const secondPromise = pauseReject('second', 2000); | |
const thirdPromise = pause('third', 1000); | |
const promises = [firstPromise, secondPromise, thirdPromise]; | |
// or create an array of promises and handle the errors in one place | |
Promise.all(promises.map(p => p.catch(err => console.log(err)))) | |
.then(([first, second, third]) => console.log('parallelErrorHandlingTogether:', first, second, third)); | |
}; | |
parallelErrorHandlingWrong(); | |
parallelErrorHandlingOneByOne(); | |
parallelErrorHandlingTogether(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment