Skip to content

Instantly share code, notes, and snippets.

@srebalaji
Last active March 23, 2019 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srebalaji/943465bae09f9c2a86af6fde6775840f to your computer and use it in GitHub Desktop.
Save srebalaji/943465bae09f9c2a86af6fde6775840f to your computer and use it in GitHub Desktop.
A sample promise all with rejection
// A simple promise that resolves after a given time
const timeOut = (t) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (t === 2000) {
reject(`Rejected in ${t}`)
} else {
resolve(`Completed in ${t}`)
}
}, t)
})
}
const durations = [1000, 2000, 3000]
const promises = []
durations.map((duration) => {
promises.push(timeOut(duration))
})
// We are passing an array of pending promises to Promise.all
Promise.all(promises)
.then(response => console.log(response)) // Promise.all cannot be resolved, as one of the promises passed got rejected.
.catch(error => console.log(`Error in executing ${error}`)) // Promise.all throws an error.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment