Sagar Medtiya
Sagar Medtiya

Sagar Medtiya

🤞Understanding Promises in JavaScript🚀

🤞Understanding Promises in JavaScript🚀

Sagar Medtiya's photo
Sagar Medtiya
·Aug 18, 2022·

3 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • What is a Promise🤞?
  • How it works⚒️?
  • Static types and prototype method:
  • Promise🤞 Chaining
  • Important points

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)=> { ... } );

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);

Output:

Screenshot 2022-08-18 112212.png After 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.png So 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"));

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);
    });

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)
    })

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🤌

Did you find this article valuable?

Support Sagar Medtiya by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this