Everything you need to know about Promises in Javascript

Saravanan Ramupillai
5 min readMay 29, 2019

--

The Javascript Promise is a crucial concept that every Javascript developer should know. Promises are crucial to asynchronous work in Js, and without a proper understanding of Promises, it is easy to get lost while reading about them. So I thought I’d explain it in a much simpler way by telling the story of an Ancient King’s life which exactly mimics how a Promise in Javascript behaves. I’ll also explain how to use Promise in various scenarios of the King’s life.

King Bob

Long long ago, A King called Bob happily ruled over his territory with his powerful servants. Whenever the King wanted to get something done, he simply gave orders to his servants. The intelligent and powerful servants will Promise the King that they will complete whatever work the King asked them to do. If they failed to complete the task because of external factors, they will come back and explain to the King why they failed.

Servant promises his King

In Javascript we will create a promise using the Promise API. Here is how above situation can be written in Javascript.

How to create and resolve promise

If you looked at the code, when the King asks the servant to prepare the horses, at line 16, the Servant creates a promise using the new Promise(handler) API and gave it to the King. A handler is a function with two arguments: one for fulfilling (resolve) and another for failing (reject) the created promise.

Now the King can check the result of the servant’s work by calling the then method (at line 29) available in the promise given by servant, by passing two functions as arguments, one function for being notified when the promise is fulfilled (servant completed the work) using the resolve method, and another function for being notified when promise is failed (servant failed to complete the work) using the reject method.

As one servant can only do one task at a time, if the King asks the servant to do two tasks, the servant will do it one after another by promising the King for the first task and upon fulfilling the first task, he will promise the King again for the second task and he/she will proceed to do the second task. But if the servant failed at his/her first task, he/she will not promise again to the King for proceeding with the second task. The servant will simply halt working.

Servant works sequentially for two independent tasks

This is exactly how we use promises to sequentially do two independent tasks in Javascript. Here is the implementation for the above situation.

Serial processing of promises

If you noticed, we introduced two new methods Promise.reject and catch. It is convention to use the catch method for error handling instead of passing a function as a second argument to then method to be notified about error. The Promise.reject method, called with the reason as a parameter, is used to create a promise which is already rejected / failed to fulfill (line 53).

Rules to Remember:

  1. A Promise will be in any one of following state at any point in time
    1. Pending (line 41)
    2. Fulfilled /Resolved (line 44)
    3. Rejected /Failed (line 50)
  2. The value returned by calling the then function is also a Promise, which resolves to whatever value we return inside the promiseFulfilled function as we did at line 45.
  3. The two static methods Promise.resolve and Promise.reject are used create a new Promise which will be immediately resolved to the value that was passed into those functions (line 53).

We will update these rules as we move forward with other Promise concepts.

Now the King has to prepare for a council meeting, so he called 3 servants and assigned them work. Each servant gives a promise to King and they begin to work. Depending on the complexity of work, each servant takes a different amount of time to finish his/her work, and returns back to tell the King that they have completed their work.

Servants works independently but for common goal

In order to know whether all the work for council meeting has been done, the King has to keep track of each individual servant’s work and check it whenever each servant comes back to tell the King that he has finished his work. If any servant failed to finish his/her work, the council meeting cannot happen. Here is the implementation.

Work Parallelism with Promise

But here is the problem, the King cannot keep track of work that each servant does since he is so busy with other work. What the King does is, he employs an Admin to manage the servants’ work. Now, the King only needs to ask the Admin about status.

Admin manages his servants, King is free to do other work

In order to implement Admin’s job, Javascript Promise provides the static method called Promise.all. The Promise.all method takes list of promises as input and waits until all of them get resolved and returns a single promise which will resolve to the value of all the input promises it has processed. In case any of the input promises fail to resolve, Promise.all will mark entire work as failed. With this feature we can now implement the Admin role in our implementation.

Managing set of independent promises for common goal

By using Promise.all, the admin’s job becomes much simpler, because co-ordinating with his servants to get work done becomes simpler. The response given by Promise.all is an array of all the servants’ results in the same order by which we co-ordinated our servants on lines 9-11.

Rules to Remember:

  1. We use Promise.all whenever we want to run independent tasks but in a combined way to achieve a common goal.

Recap:

We have seen

  1. How to create a promise
  2. Processing promises in sequence
  3. Processing promises in parallel with and without Promise.all
  4. How to create immediately resolvable promise using Promise.resolve / Promise.reject

and when to use what approach with the King’s life story. I hope you enjoyed the story.

--

--