DEV Community

Cover image for Promises in Javascript
Deepansh Bhargava
Deepansh Bhargava

Posted on

Promises in Javascript

A Promise represents the state of an asynchronous operation. This asynchronous operation can be anything i.e fetching data from an API, reading contents from a file, etc.

Before promises we had callbacks, but they had fewer capabilities and lead to a sloppy code. When dealing with multiple callbacks, our code will become a callback hell which becomes difficult to manage.

A Javascript Promise consists of four states:

  1. Fulfilled: The operation was completed successfully.
  2. Pending: The operation isn't completed, it's still in process.
  3. Rejected: The operation is failed.
  4. Settled: The operation is either fulfilled or rejected.

A promise can be created by using
Promise constructor.

const isNumEven = (num) => new Promise((resolve, reject)=> {
  if(num % 2 === 0) {
    resolve(true)
  } else {
    reject(false)
  }
})
Enter fullscreen mode Exit fullscreen mode

Now the above-created promise can be used as

isNumEven(5)
  .then(res => console.log(res))
  .catch(err => console.log(err))          
Enter fullscreen mode Exit fullscreen mode

The then handler is invoked when the promise is fulfilled while the catch handler is invoked when the promise is rejected.

Here in this case the catch handler is invoked as the number we have passed to the function is not even.

Chaining Promises

When the result of a promise is another promise, we have to chain them to get the results.

isNumPrime(5)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.log(err))           
Enter fullscreen mode Exit fullscreen mode

This method of handling asynchronous operations looks fine when we have 2 to 3 promises but it gets unmanageable when there are more than that. Then async await comes into the picture. They help you to handle multiple promises very easily.

That's it for now. Thanks for making it to the last. Let me know any feedback or suggestions you have for this article. Also, let me know if you want me to write on async await.

Top comments (4)

Collapse
 
nancyjain0631 profile image
Nancy Jain

Simplest explanation for javascript promises. Thanks for sharing.

Collapse
 
thekrprince profile image
Kumar Prince

Nice explanation 👍

Collapse
 
fpert041 profile image
Francesco Perticarari

Agree, well explained. You should definitely attempt with async await

Collapse
 
deepansh946 profile image
Deepansh Bhargava