JavaScript Promise:

Let's deep dive into promises:

Promises are used to handle asynchronous operations in JavaScript.

We will discuss with a code example how things used to work before Promises and then how it works after Promises

Take an example of E-commerce:

Q: How to fix the above issue?
A: Using Promise.

Now, we will make createOrder function returns a promise and we will capture that promise into a variable

Promise is nothing but we can assume it to be an empty object with some data value in it, and this data value will hold whatever this createOrder function will return.

Since createOrder function is an async function and we don’t know how much time will it take to finish execution.

So the moment createOrder will get executed, it will return you a undefined value. Let’s say after 5 secs execution is finished so now orderId is ready so, it will fill the undefined value with the orderId.

In short, When createOrder gets executed, it immediately returns a promise object with undefined value. then javascript will continue to execute with other lines of code. After sometime when createOrder has finished execution and orderId is ready then that will automatically be assigned to our return promise which was earlier undefined.

Promise.then Function:

Q: The question is how we will get to know response is ready?
A: So, we will attach a callback function to the promise object using then to get triggered automatically when result is ready.

Callbacks vs Promises:

Callbacks:

Here, we are passing the callback function to another function. In this case, we just passed the function and now createOrder would have called whenever it wants to.

Here, we are attaching a callback function to a promise object. In this case, we will have the control of program with us. Promise guarantee, it will callback the attached function once it has the fulfilled data. And it will call it only once. Just once.

Earlier we talked about promises are objects with empty data but that’s not entirely true, Promises are much more than that.

Promise Object in browser:

When we call an asynchronous function, i.e., a function that might send a response in the future, you are actually taking a promise. At first, the promise remains in the PENDING state because no response has been received. After some time, when the response is received, there are two possible cases:

  1. We got a response (i.e., the promise goes to the FULFILLED state)

  2. We got an error and no response (the promise got REJECTED)

Note: Getting a response means the promise is in the SETTLED state. In other words, the promise is not in the PENDING state now, and it has been either RESOLVED or REJECTED.

How Promises Work

In technical terms, a promise is an object that is returned as a response to an asynchronous function. It can be one of these four possible states:

  1. PENDING

  2. FULFILLED

  3. REJECTED

  4. SETTLED

Let us understand this in a bit more detail. The moment a promise is invoked, it goes to the PENDING state and waits for a response to come. We might get the correct response, which makes the promise FULFILLED, or we might get an error, i.e., the promise goes to the REJECTED state. A promise is said to be SETTLED if it is not in the pending state, i.e., either the response has arrived or an error has occurred.

Note: Once settled, a promise cannot be resettled.

Benefits of Promises

  • Promises are better than Callbacks as callbacks create a situation called callback hell

  • Code is readable and better maintained when promises are used to handle async code than when callbacks are used.
    EndFragment

Promise Objects are immutable:

Whenever it is fulfilled and whenever we have data inside our promise object, we can just pass it here and there in our code and we don't have to worry about that someone can mutate the data. We have control over this. Nobody can mutate this, it's immutable.

Interview Questions:

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

Promise Chaining:

Above code is also known as the "Pyramid of DOM".

What is Promise Chaining:

We use asynchronous functions which return promises and use resolve values with the help of .then. And that value we further use in another asynchronous function within another .then block and so on. At last, we give .catch block for handling errors. If there is any one error in any asynchronous function, it will be handled by the .catch block. This method of writing .then methods continuously one after another is known as 'promise chaining'.

Takeaways:

Firstly we have learned how we can handle asynchronous code using using callbacks and there is a major issue in these callbacks while using callbacks i.e inversion of control (We were passing functions inside another API and we are giving control of one API to another API which we wanted to avoid i.e. inversion of control) and to handle asynchronous tasks effectively we have promises in JavaScript. And here we don't pass a function to another function, but we attach a function to a promise object. When a promise is triggered, it is in the Pending state. After some time, this asynchronous task might be completed and returned with one of these statuses - fulfilled or rejected.

  • A promise fulfilled or rejected is said to be in the SETTLED state. Once settled, a promise cannot be resettled.

  • How does the browser get to know when a promise gets a response? We have the following methods for the same.

    • .then()

    • .catch()

    • .finally()