Promises in Javascript

Promises in Javascript

If you belong to the group of people who have heard about promises but do not know what it is, then you have landed at the right place.

What is a promise?

Promise is like a proxy object that represents a value that will be available at a future point of time. This object will be available as a result of some asynchronous computation, asynchronous call to an api or any operation that will happen in near future, the value of which is not known at the given point of time.

How to write a promise in javascript?

The promise object accepts a callback  function with two argument functions. We have a resolve function that executes if the task of that promise is successful and we have a reject function that executes if the task of the promise is unsuccessful.

Every promise object has a then function that executes after the promise is executed(resolved or rejected). This accepts two callback functions. The first function is for successful resolution of the promise. It accepts any argument that you pass to the resolve function in the promise object. The second function is for rejection in the execution of the promise and it accepts any argument that you pass to the reject function in the promise object. Alternatively you can have a then function that accepts only one argument that is for resolution of the promise and chain a catch function that works for the rejection of the promise.

Once the task mentioned in the promise is executed it will execute and return the result of the corresponding resolve or reject function.

In the below example I have hard coded the status(to reduce complexity of code and emphasize on the concept on promise) which can be considered as the result of executing any asynchronous task. If the status is true the resolve function will be executed and if the status is false the reject function will be executed.


Chaining of promise

You can chain promises like you do for functions. You can chain the ‘.then’ function with each returning data for the next ‘.then’ function to consume


Promise has a ‘.all’ method which takes the argument as an array of promises. This method is executed only if all the promises are resolved. Sometimes you want a task to be executed after all the promises are resolved. You can use this function for that purpose


//Code to be executed once promise1 and promise2 are executed



Promise has a ‘.race’ method which executes once any one of the promises passed to it as an array are executed.


//Code to be executed once either promise1 or promise2 are executed

  • Dhairya Vora

    can you also explain/contrast it with observables?

    • Thanks for writing. Added a few new points with examples.

Comments are closed.