Yet Another Introduction To Promises(By Code Examples)

Yet Another Introduction To Promises(By Code Examples)

And always keep your promises

·

2 min read

Hello World,

Today I want to share some code snippets about Promises in Javascript. Basically it is about Promise functions. You can find code explanations on the code blocks. I do not want to get into Promise details.(What is a promise? What is executor function in Promise constructor? etc...). You can easily find much more detailed information here . Let's jump into the code :)

const p1 = new Promise((resolve,reject) => setTimeout(
 () => resolve("p1 resolved"),1000));
const p2 = new Promise((resolve,reject) => setTimeout(
() => reject("p2 rejected"),2000));
const p3 = new Promise((resolve,reject) => setTimeout(
() => resolve("p3 resolved"),3000));
const p4 = new Promise((resolve,reject) => setTimeout(
() => reject("p4 rejected"),4000));


//With Promise.all if any promise rejected then first rejected promise
//value will be passed to catch clause then section will not be executed at all. 
//if every promise resolved their values will be passed to then 
// clause at corresponding order

//output: -> "p2 rejected"
Promise.all([p1,p2,p3,p4])
.then(([val1,val2,val3,val4]) => console.log(val1,val2,val3,val4))
.catch(err => console.error(err) )

//Promise.allSettled will wait all the promise to settled(resolved or rejected).
//for resolved promise return {status: "fulfilled", value: "p1 resolved"}
//for rejected promise return {status: "rejected", reason: "p2 rejected"}
Promise.allSettled([p1,p2,p3,p4])
.then(([val1,val2,val3,val4]) => console.log(val1,val2,val3,val4))
.catch(err => console.error(err) )


//Promise.race will return first settled(resolved or rejected) promise's value
//output -> First resolved promise value is : p1 resolved
Promise.race([p1,p2,p3,p4])
.then(val => console.log(`First resolved promise value is : ${val}`))
.catch(val => console.log(`First rejected promise value is: ${val}`))


//Promise.any returns first resolved promise value. Does not take 
//rejected promises into account
Promise.any([p1,p2,p3,p4])
.then(val => console.log(`First resolved promise value is : ${val}`))

Stay tuned, Bye bye

Did you find this article valuable?

Support Chety's Blog by becoming a sponsor. Any amount is appreciated!