DEV Community

Akshat Sharma
Akshat Sharma

Posted on

Day 23 of 30 of JavaScript

Hey reader👋 Hope you are doing well😊
In the last post we have talked about Callbacks. In this post we are going to discuss about Promises.
So let's get started🔥

Promises

Promises are used to handle Asynchronous Operations preventing callback hell and unmanageable code. A Promise is an object that will produce a single value some time in the future. If the promise is successful, it will produce a resolved value, but if something goes wrong then it will produce a reason why the promise failed.
It is something like when you make a promise either you fullfill it or tell your reasons why you didn't able to fullfill it.
Image description
So this is an example of Promise. If the condition is true resolve method is called else reject() method is called. If promise is fullfilled then "success" is printed else an error is caught.
Note that we resolve method is utilized in .then and reject in .catch.

How to create a Promise?

To create a promise, you need to create an instance object using the Promise constructor function. The Promise constructor function takes in one parameter. That parameter is a function that defines when to resolve the new promise, and optionally when to reject it.
Image description
In promises, resolve is a function with an optional parameter representing the resolved value. Also, reject is a function with an optional parameter representing the reason why the promise failed.
Image description

States of Promise

  • pending: This is the default state of a defined promise

  • fulfilled: This is the state of a successful promise

  • rejected: This is the state of a failed promise

Callback in Promises

To use a callback in Promise we need to use .then method. This method takes in two callback functions. The first function runs if the promise is resolved, while the second function runs if the promise is rejected.
Image description

How Promises eliminate Callback hell

Promises are a good way to eleminate callback hell as they use .then() which returns a promise either fullfilled or rejected hence eliminating "Pyramid of Doom".
Image description
The above code will lead to Callback hell. Let's use Promise to resolve this issue.
Image description
Now here you can see that we no more have callback syntax and whenever a promise fails we have a rejected promise and we will stop here to check for errors.

Handle Errors in Promise

To handle errors in Promises, use the .catch() method. If anything goes wrong with any of our promises, this method can catch the reason for that error.
Image description

Handling multiple Promises at once

When we have multiple promises we can run all in parallel at once. The methods through which we can achieve this are -:

  • Promise.all()
  • Promise.race()
  • Promise.any()
  • Promise.allSettled()

Promise.all()
Promise.all() accepts an array of promises as an argument but returns a single promise as the output.
Image description
The single promise returns resolves with an array of values if all the promises in the input array are fulfilled.If at least one promise in the input array does not resolve, Promise.all() will return a rejected promise with a reason. The reason of rejection will be same as the promise that is rejected.
Promise.all() will run all the input promises before it returns a value. But it does not run the promises one after the other–instead it runs them at the same time.
This is why the total time it would take Promise.all() to return a value is roughly the time it would take the longest promise in the array to finish.

**Promise.race()**
Promise.race() returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
Image description
Here as first promise is resolving fastly that is why first is printed.
If the promise with the shortest execution time happens to be rejected with a reason, Promise.race() returns a rejected promise and the reason why the fastest promise was rejected.

**Promise.any()**
Promise.any() accepts an array of Promises as an argument but returns a single Promise as the output. The single promise it returns is the first resolved promise in the input array. This method waits for any promise in the array to be resolved and would immediately return it as the output.
Image description
If none of the promises in the array are resolved, Promise.any() returns a rejected promise. This rejected promise contains a JavaScript array of reasons, where each reason corresponds with that of a promise from the input array.

Promise.allSettled()
Promise.allSettled() is used when we want to wait for all promises to complete regardless of whether they are fulfilled or rejected.
Image description
Promise.allSettled() is similar to Promise.all() in that all their input promises must settle before the promise they return has a settled state—fulfilled or rejected.
The difference is Promise.all() can only be successful if all the promises in the input are resolved, while Promise.allSettled() does not care about the status of the input promises.

So this was all about Promises. Now you have better understanding of Promises. In the next blog we will discuss about Async/Await. Till then stay connected and follow me.
Thankyou 🩵

Top comments (6)

Collapse
 
ezpieco profile image
Ezpie

Talk about JavaScript, that's a promising return... now that's a JS joke.

If you ask me, knowing promises in JavaScript are quite indeed an important topic. If you get promises you can understand most of JS, because for some reason handling promises and async calls is what mostly is done with JS in big tech companies, I mean who uses JavaScript to make an IDE? Ah... yeah excluding Microsoft for obvious reasons.

Collapse
 
akshat0610 profile image
Akshat Sharma

I will definitely check it out

Collapse
 
enoch91 profile image
Enoch Osarenren

Hello everyone, I hope you're all doing well. I recently launched an open-source project called GraphQLPlaceholder, and I'd love your support. Please check it out and give it a star on GitHub github.com/enochval/graphql-placeh.... Your support would mean a lot to me and help immensely in the project's growth.

Thank you.

Collapse
 
codehost profile image
CodeHost

Great Work!