I “Promise” that u will understand promises in JS forever 😜
Published: 2023-08-15 16:41:31


We all know that JavaScript is a synchronous programming language. But callback functions help to make it an asynchronous programming language.

No matter how helpful the callback functions were in JS, they came with their own problems and pain points. And trust me “callback hell” is not the biggest pain point of it. So u wonder what is… it is none other than “inversion of control”. Let’s not waste time in understanding all the disadvantages of them, you guys are smart enough to google(ChatGPT/Bard) the terms and understand.

But as the callback functions are so troublesome, we came up with the Promises in JS. Let us understand promises in a very easy way from the example below!

Promises are like a waiter.
They promise to bring you food, but it takes time.
While you wait, you can do other things.
If the food is ready, the waiter brings it to you.
If the food is not ready, the waiter tells you.
In other words, promises are a way to handle asynchronous operations in JavaScript. Asynchronous operations are operations that do not block the main thread of execution. This means that you can perform multiple asynchronous operations at the same time, and your page will not become unresponsive.


Promises are just an easier way to manage the Async Operations in JS.
The Promise the object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

From the above example, we can see that, promises in JS are similar to the commitments we make in our daily lives.

Promises are mainly used to increase the readability of the code. Promises make the code more clean and more manageable. It is considered a good practice to use Promises.

A Promise has three states:

Pending: The promise is not yet completed.
Fulfilled: The promise has been completed successfully.
Rejected: The promise has completed with an error.

Now let us see how to create promises:-
We can create a promise using the new Promise() constructor. The constructor takes two arguments: a resolve function and a reject function. The resolve function is called when the promise is fulfilled, and the reject function is called when the promise is rejected.

Here is an example of how to create a promise that resolves with the number 10:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(10);
  }, 1000);
});
How to use promises
We can use the then() method to handle the fulfillment or rejection of a promise. The then() method takes two arguments: a callback function that is called when the promise is fulfilled, and a callback function that is called when the promise is rejected.

Here is an example of how to use the then() method to handle the fulfillment of the promise we created above:

promise
  .then((value) => {
    console.log(value); // 10
  })
  .catch((error) => {
    console.log(error); // Error: The request timed out
  });
In this example, the then() method will call the first callback function when the promise is fulfilled. The first callback function will log the value of the promise, which is 10. If the promise is rejected, the then() method will call the second callback function. The second callback function will log the error message.

The Promise the object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

Helper Functions related to promises:

1) Promise.All
The Promise.all(iterable) the method returns a single Promise that resolves when all of the promises in the iterable argument have resolved or when the iterable argument contains no promises. It rejects with the reason of the first promise that rejects.

2) Promise.race

The Promise.race(iterable) the method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.

Key Points to remember:- 
1) Use promises whenever you are using async or blocking code.

2) A promise is an object that returns a value in the future.

3) A promise starts in the pending state and ends in either a fulfilled state or a rejected state.

4) resolve maps to then
           &
   reject maps to catch

5) If something needs to be done in both cases use .finally

**Conclusion**

Promises are a way to chain asynchronous operations cleanly without deeply nested callbacks.

Promise.All — It waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, it becomes the error of Promise.All, and all other results are ignored.

Promise.AllSettled — It waits for all promises to settle and returns their results as an array of objects, and they can be individually either resolved or rejected.

Promise.Race — It will return the promise instance which is firstly resolved or rejected. 

That’s a wrap for this one. Stay tuned for further blogs on more advanced JavaScript concepts!