Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save antonga23/474cd87a647039795b4db2e043dbb005 to your computer and use it in GitHub Desktop.
Save antonga23/474cd87a647039795b4db2e043dbb005 to your computer and use it in GitHub Desktop.
Promise.all error handling
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