Skip to content

Instantly share code, notes, and snippets.

@arifmahmudrana
Created January 22, 2020 11:12
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 arifmahmudrana/504788cdaaaafdade97fe47f8a39de18 to your computer and use it in GitHub Desktop.
Save arifmahmudrana/504788cdaaaafdade97fe47f8a39de18 to your computer and use it in GitHub Desktop.
Promise all
/*
* If used Promise all first error will go to catch block
*
* If no error occurs then the resolved values will be an array
with exact sequence of promise here e.g if run Promise.all([p1, p2, p3])
output: [ 'one', 'two', 'three' ]
*
* If there is a setTimeout after all setTimeout execution will be done
*
* If there is a setTimeout, setImmediate or setTimeout 0 thoose will be executed after next tick
*/
const p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('one'), 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve('two'), 2000);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve('three'), 3000);
});
const p4 = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('p4')), 4000);
});
const p5 = new Promise((resolve, reject) => {
reject(new Error('p5'));
});
const p6 = new Promise((resolve, reject) => {
reject(new Error('p6'));
});
// Using .catch:
Promise.all([p1, p2, p3, p4, p5, p6, Promise.reject('p7')])
.then(values => {
console.log(values);
})
.catch(error => {
console.error(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment