DEV Community

Sagar Medtiya
Sagar Medtiya

Posted on • Originally published at blog.sagarmedtiya.me on

🤞Understanding Promises in JavaScript🚀

image

What is a Promise🤞?

By the definition of MDN,

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

We know that JavaScript is a synchronous programming language but callback function makes it Asynchronous.

Let's understand promise by simple example, suppose you made a promise🤞 to yourself that you will wake up at sharp 5AM. But eventually, you don't know whether you will make it or not, that means either you are going to complete that promise or not.

How it works?

The promises returns one of the 3 possible states:

  • Fullfilled: You woke up at sharp 5AM.
  • Rejected: You didn't wake up at 5AM.
  • Pending: You don't know if you'll wake up or not.

A promise is settled if it's not pending means it has been resolved or rejected. After it has been settled there is no use of calling resolve() or reject().

Syntax📃

new Promise( (resolve, reject)=> { ... } );

Enter fullscreen mode Exit fullscreen mode

For example📃 ,

let wakePromise = true;
let wakeUp = new Promise((resolve, reject)=> {
    setTimeout(() => {
        if (wakePromise) {
        resolve('I woke up');
    } 
    else {
        reject('I didnt wake up'); }
    }, 5000);
});
console.log(wakeUp);

Enter fullscreen mode Exit fullscreen mode

Output:

Screenshot 2022-08-18 112212.pngAfter completion of 5 seconds the promise gets fulfilled.

Screenshot 2022-08-18 113014.png

If we change wakePromise = false then it returns,

Screenshot 2022-08-18 113414.pngSo the reject method moved the promises to the rejected() state.

Static types and prototype method:

  • Promise.prototype.then(onFulfilled, onRejected)

.then method is used to schedule📅 a callback to be executed when the promise is successfully resolved.

  • Promise.prototype.catch(onRejected)

.catch method is used to schedule📅 a callback to be executed when the promise is rejected.

  • Promise.prototype.finally(onFinally)

.finally is used to execute the same piece of code whether the promise is fulfilled or rejected.

For example📃 ,

function makePromise(wakeUp) {
    return new Promise(function (resolve, reject) {
       setTimeout(() => {
           if (wakeUp) {
               resolve("I woke up at 5AM.");
           } else {
               reject("I didn't wake up at 5Am.");
           }
       }, 5 * 1000);
   });
   }
   let wakeUp = makePromise(true);
   wakeUp
       .then(success => console.log(success))
       .catch(reason => console.log(reason))
       .finally(() => console.log("Let's sleep"));

Enter fullscreen mode Exit fullscreen mode

Output:

Screenshot 2022-08-18 131219.png

Promise🤞 Chaining

Promise Chaining is a concept by which we may initialize another promise inside our .then() method and accordingly we may execute our results.

For example📃 ,

let promise = new Promise((resolve, reject) => {
    resolve("Test");
  });
  promise
    .then(
      new Promise((resolve, reject) => {
        resolve("exams");
      })
      .then((result1) => {
        console.log(result1);
      })
    )
    .then((result2) => {
      console.log(result2);
    });

Enter fullscreen mode Exit fullscreen mode

Output:

Screenshot 2022-08-18 161853.png

We can use promise.all() for the nested .then method. It can simply the messy code easily. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

For example📃 ,

const Promise1 = new Promise((resolve, reject)=>{
    setTimeout(() => {
        console.log('The first promise has resolved');
        resolve(10);
      }, 1 * 1000);
})
const Promise2 = new Promise((resolve, reject)=>{
    setTimeout(() => {
        console.log('The second promise has resolved');
        resolve(10);
      }, 1 * 1000);})
Promise.all([Promise1, Promise2])
    .then((data)=>{
        console.log(data);
    })
    .catch((error)=>{
        console.log(error)
    })

Enter fullscreen mode Exit fullscreen mode

Output:Screenshot 2022-08-18 161853.png

Important points

  • Use promises whenever you are using async or blocking code.
  • A promise is an object that returns a value in the future.
  • A promise starts in the pending state and ends in either a fulfilled state or a rejected state.
  • resolve maps to then and reject maps to catch
  • If something needs to be done in both cases use .finally

Thanks for reading my post. I hope you've liked it. Happy coding😊

Some more blogs by me💗

Some best techniques to Optimize your React App🐱💻

Component Lifecycle🌀 in ReactJS🚀

Know Your JavaScript🤌

Top comments (0)