April 9, 2024

Master JavaScript Promises

The best time to establish protocols with your clients is when you onboard them.

Heading

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse varius enim in eros elementum tristique. Duis cursus, mi quis viverra ornare, eros dolor interdum nulla, ut commodo diam libero vitae erat. Aenean faucibus nibh et justo cursus id rutrum lorem imperdiet. Nunc ut sem vitae risus tristique posuere.

Synchronous Operation

  • Synchronous operations execute one after the other in a sequential manner.
  • Each operation must be completed before the next one starts.
  • The program is blocked or paused until each operation finishes.

Asynchronous Operation

  • Asynchronous operations allow other tasks to run while waiting for an operation to complete.
  • The program does not wait for the completion of the current operation and continues with the next one.
  • Asynchronous operations often use callbacks to handle the result of the operation when it’s ready.

Promise

Promises are used to handle asynchronous operations in a more structured and readable manner. They provide a way to represent and work with values that might be available now or in the future.

In JavaScript, synchronous code executes in a straightforward, step-by-step manner, while asynchronous code allows certain tasks to be deferred, typically to handle I/O operations, timers, or events.

Promises help manage asynchronous code by providing a consistent and standardized way to handle the result or failure of an asynchronous operation. They make it easier to reason about the flow of the program and handle errors in a more centralized manner.

States of Promise

A promise has three states which are as following:

  • Pending (Always first state)
  • Fulfilled
  • Rejected

When the promise is initiated it goes into pending state and thereafter it goes to one of the remaining states i.e. either fulfilled or rejected, so when we say that the promise is settled, it means that the asynchronous operation is done and it’s either fulfilled or rejected.

In simpler words, fulfilled state means our operation is successfully done and we have achieved the result, rejected means some error has occurred while performing the operation. So now what one may want to perform some operation if promise is fulfilled and also error handling if promise is rejected, now how can one do that?

Methods to handle settled (fulfilled or rejected) state of promise:

  • then(): this method is used when a promise is fulfilled.
  • catch(): this method is used when a promise is rejected.

Before going deep into handling the promise let’s first understand how to create a promise:

In the above figure we have syntax to create a promise. I have used a function that returns a promise you can directly use from line number 2. What this promise does is if the value is an odd number it rejects the promise after 2 seconds and returns error, if the value is even it fulfills the promise after two seconds and returns the value itself.

So here the resolve() method is used to make a promise fulfilled and the reject() method is used to make a promise rejected. So in simpler words whatever value you will pass to resolve the promise will get fulfilled with that value and whatever value you will pass to reject the method the promise will get rejected with that value.

Now let’s call this promise and see how can we use .then() and .catch() method on it:

.then() example

In the above figure you can see that we have called the function with an even value and as per the definition of our function the promise should be fulfilled because we passed an even number. In the terminal you can see that the output is “Hi I am from then method 2”. Which means then() method got executed. So then() method expects a callback with one argument. You can name the argument anything you want, we named it result.

.catch() example

In the above figure you can see that we have called the function with odd value and as per the definition of our function the promise should be rejected because we passed an odd number. In the terminal you can see that the output is “Hi I am from catch method” followed by the error. Which means the catch() method got executed. So the catch method also expects a callback with one argument. You can name the argument anything you want, we named it as error.

Handling array of promise

To handle array of promise we have multiple ways, below are some most commonly used methods:
1. Promise.all()

2. Promise.any()

3. Promise.allSettled()

Promise.all():

It expects an iterable of promises as an input and it returns a single promise. As it returns only a single promise now you may think when that single promise will be resolved, with what value and when does it get rejected. The output promise is supposed to be resolved when all the promises in the list gets resolved, on the other hand the moment any promise in the list get rejected the output promise becomes rejected as well. So we should use promise.all() when we want all the promises in the list to get resolved.

In the above example you can see we have passed list of promises in line 25, and since we passed all the value less than 5, so the entire promise get resolved and we have handled the output in the .then() block, so here the response in .then() block you will get is an array and each value of array is the value with which respective promise get resolved. You can modify the above code by passing any value greater than 5 and can see that how the promise is getting rejected.

Promise.any():

Just like Promise.all(), it also expects an iterable of promises as an input and it returns a single promise. This returned promise fulfills when any of the input’s promises fulfills, with this first fulfillment value. It rejects when all of the input’s promises reject (including when an empty iterable is passed). Unlike Promise.all() which returns a list of values, Promise.any() returns only the first promise value which gets resolved. Let’s see the above example with Promise.any():

In the above example you can see we have passed list of promises in line 24, and this time you can see we get ‘1’ as an output not any list, so basically it tells us that the first promise got resolved therefore the output promise gets resolved with first promise value.

Note: Promise.any() will get rejected only if all the promises in the list gets rejected, if at least one of the promise gets resolved it will result the output promise to be resolved as well.

Promise.allSettled():

Just like above two methods, it also expects an iterable of promises as an input and it returns a single promise. The output promise get resolved when all the promises in the list gets settled (No matter whether they are rejected or fulfilled they just need to get settled). Let’s see the example:

Here you can see that I made the first promise to get rejected as I passed a value which is greater than 5, again here as all of our promise got resolved the .then() block gets executed. The output is again the list of an object, each object contains a field “status” which can take a value “rejected (if that particular promise gets rejected)” and another value “fulfilled (if that particular promise gets fulfilled)”, if the status is fulfilled that object will have “value” field as well which will have the value with which the promise got resolved.

To know more methods about promises you can check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all.

CodeStax.Ai
Profile
April 8, 2024
-
6
min read
Subscribe to our newsletter
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Share this article:

More articles