Skip to main content

Command Palette

Search for a command to run...

Promises

Updated
โ€ข6 min readโ€ขView as Markdown

Let's First know what is the Async in JS

Shubham's mid semester exam started on day after tomorrow but he did not complete his DBMS's assignment also and whose last date of submission is tomorrow. Now he have two task one is preparing for exam and another doing this uncompleted DBMS's assignment. So he takes help from his beautiful friend "Rashi". He ask from her to write his assignment so he can prepare for his exam, Rashi is very good in studies and do her work on time. she already submit her assignment and study for exam so she agree to do Shubham's DBMS assignment. Now Shubham outsource the help and do the both work on time on simultaneously.
Similarly JS out-source the some thing and do all work simultaneously, to do this async behavior of promises help the JS.

What is Promise ?

Shubham scrolling reels on instagram and he saw on of the reel of the movie Dhurandhar and then getting more and more reels and review of the Dhurandhar movie so he excited to watch the movie then he talk to his friend Rashi lets go and watch the Dhurandar movie I saw the review movie is good then after some convincing by him Rashi agree to go mall and watch Dhurandar movie But Rashi always cancels the plan so he decide to take a promise from Rashi to come for movie. Now promise is pending, this will be the Async work of the Shubham his work continuously will be done by his team.

Promise States

Promise have the 3 states
a) Pending
b) Fulfill(resolve)
c) Rejected(cancled)

  • Pending: We did promise now only that we will go for movie. When we create the promise that always be in pending state.

  • Fulfill: We finally go for movie and watch and came back that means our promise fulfill same in JS promise is successfully resolved

  • Rejected: Sad she cancel the movie plan and our promise is rejected

Creation of Promise

let goForMovie = new Promise((resolve, reject) => {
    let isWeGo = true;
    if (isWeGo) {
        resolve("Yaa Yaa we go for movie!๐Ÿ˜");
    } else {
        reject(new Error("Oops! We can't go to the movie she cancle it ๐Ÿ˜”."));
    }
});

We use the new key word for creating the promise and this takes the call back in that callback it take the two thing one is resolve (fulfill --> movie k lya jaye ge ๐Ÿ˜๐Ÿ‘๐Ÿป) and another is rejected( next day vo busy thi jan nahi paye ๐Ÿ˜ญ ). We can also give the only one parameter also if we know ki Shubham k dost paka jaye ga move k lya tho we can give only resolve if we know ki y defiantly jaye ga hii nahi tho we can give the reject also.

Consumption of Promise

let goForMovie = new Promise((resolve, reject) => {
    let isWeGo = true;
    if (isWeGo) {
        resolve("Yaa Yaa we go for movie!๐Ÿ˜");
    } else {
        reject(new Error("Oops! We can't go to the movie she cancle it ๐Ÿ˜”."));
    }
});

goForMovie.then((message) => {
    console.log("we finaly go for movie๐ŸŽ‰",message);
}).catch((error) => {
    console.error("she cancle it ๐Ÿ˜ญ",error.message);
});

for consuming the promises we have the .then which take the value of resolve y fir rejecte from the promises and then jo bii return hota hai .then k ander jo bi function hoga uss me as a parameter pass kr deta hai .then

Here is the complete Time line of Shubham

// Shubham having breakfast 
console.log("โฐ 8:00 - 8:30 AM");
console.log("๐Ÿณ Shubham is having Breakfast...");
console.log("โœ… Breakfast Done!\n");

// Shubham is doing some work (Coding)
console.log("โฐ 8:30 - 11:00 AM");
console.log("๐Ÿ’ป Shubham is Doing some work (Coding)...");
console.log("โœ… Work Done!\n");

// ASYNC --> Shubham is going for movie
console.log("โฐ 11:00 - 12:00 PM");
console.log("๐ŸŽฌ Shubham is going for movie...");

let goForMovie = new Promise((resolve, reject) => {
    let isWeGo = true;
    if (isWeGo) {
        resolve("Yaa Yaa we go for movie!๐Ÿ˜");
    } else {
        reject(new Error("Oops! We can't go to the movie she cancle it ๐Ÿ˜”."));
    }
});

// SYNC --> Team continues working independently

console.log("Shubham's Team is doing their work...");
console.log("Team completed the work!\n");

// consumption of promise
goForMovie.then((message) => {
    console.log("we finaly go for movie๐ŸŽ‰",message);
}).catch((error) => {
    console.error("she cancle it ๐Ÿ˜ญ",error.message);
});

Promise Methods

  1. Promise.resolve()
    Rashi movie k lya mann gyi jb Shubham ne bola he know that when he said she will be ready to go for movie. When we want to return the resolve promise
const goForMovie = Promise.resolve("Man gyi movie k lya ๐Ÿ˜");

goForMovie.then(data => console.log(data)); // yaa yaa we will go for movie
  1. Promise.reject()
    Shubham know that she will reject to go on movie. Creates a promise that is already rejected.
const goForMovie = Promise.reject("mna kre gii ");

goForMovie.catch(err => console.log(err)); // mna kr dya
  1. Promise.all()
    Shubham ask for movie and then for lunch to Rashi if any one of them get rejected then promise is rejected ๐Ÿฅฒ, if both promise get fulfill then promise is resolved ๐Ÿ˜ .
    โœ”๏ธ Resolves when all succeed
    โŒ Rejects if any one fails

    const p1 = Promise.resolve("Going for watching movie");
    const p2 = Promise.resolve("after movie we go for lunch");
    
    Promise.all([p1, p2])
      .then(values => console.log(values)); 
      .catch((error) => {
        console.error("she cancle it ๐Ÿ˜ญ",error.message);
    });
    
  2. Promise.any()
    Shubham ask for movie and then for lunch to Rashi if any one of them get fulfill then promise is resolved ๐Ÿ˜. She agree for lunch not for movie we get the success.

const p1 = Promise.reject("Going for movie");
const p2 = Promise.resolve("Going for lunch");

Promise.any([p1, p2])
  .then(result => console.log(result))
  .catch(error => console.log(error));

Output will be "Going for lunch" Even though p1 failed, it ignored it and returned the first success.

  1. Promise.allSettled()
    Shubham wait for all promise he do with her friend Rashi, regardless of mane gi y nahi.
const p1 = Promise.resolve("Going for movie");
const p2 = Promise.reject("Going for lunch");

Promise.any([p1, p2])
  .then(results => console.log(results));

//Output will be 
[
  { status: 'fulfilled', value: 'Going for movie' },
  { status: 'rejected', reason: 'Going for lunch' }
]

Used when you want results of all promises, even failed ones.