DEV Community

Cover image for Mastering promises: JS
Rahul
Rahul

Posted on

Mastering promises: JS

Ladies and Gentleman, In this post we will understand and master Promises in JavaScript.

What's a Promise? 🧐

A Promise object represents the eventual completion or failure of an asynchronous operation. In simple language, a Promise is data returned by asynchronous functions.

let promise = new Promise((resolve, reject) => {
  // Do something...
});
Enter fullscreen mode Exit fullscreen mode

Promise States πŸ€”

A promise can have one of these states:

  • Pending: This is the initial state
  • Fulfilled: Operation completed successfully
  • Rejected: Operation failed

Resolve / Reject

The Promise constructor takes in one argument: a callback with two parameters-resolve and reject.

  • **resolve **when the Promise was fulfilles
  • **reject **when something didn't work (e.g. an error ocurred)

General Structure 😳

Take a look at how a Promise is generally structured:

let promise = new Promise((resolve, reject) => {
  // Do something...

    if(/* Everything went fine */) {
      resolve("Task successful!");
    } else {
        // Well... something went wrong
         reject("Something went wrong!");
     }
});

Enter fullscreen mode Exit fullscreen mode

NOW, LET'S RUN THE PROMISE FROM THE ABOVE CODE 😐

promise
  .then((message) => {
     // Print out the message if the
     // promise is fulfilled
     console.log(message);
    })
    .catch((error) => {
       // Catch error is one occurred
       console.log(error); 
     });
Enter fullscreen mode Exit fullscreen mode

Here is a simple example of using Promise

let promiseToWashDishes = new Promise((resolve, reject) => {
  // whether the dishes are clean or not
  let clean = true; 

   if(clean) { 
      // Resolve promise if the dishes are clean
      resolve("The dishes are clean!");
     } else {
        // Reject the promise if the dishes are dirty
        reject("The dishes are still dirty!"); 
      }
});
Enter fullscreen mode Exit fullscreen mode

Let's run our example Promise:

promiseToWashDishes
   .then((result) => {
     console.log(`Great! ${result}`);
      // Great! The dishes are clean !
   })
   .catch((result) => {
    console.log(`Oh no! ${result}`);
       // Oh no! The Dishes are still dirty!
    });
Enter fullscreen mode Exit fullscreen mode

Real World Example 🀩

Chances are, you have already worked with the Fetch API! It uses Promises, too:

fetch("https://example.com/")
   .then((response) => response.json())
   .then((data) => {
   // Do something with the data...
   })
   .catch((error) => {
     // Something went wrong during the request!
    });
Enter fullscreen mode Exit fullscreen mode

Need Help

Need help in raising fund to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.


1.png




😁Thanks For Reading | Happy Coding ⚑

Top comments (0)