Promises in JavaScript

So you want to write Asynchronous code in JavaScript but don't understand promises. Well I have got you covered. In this blog we will be discussing about -

  1. What are Promises in JavaScript? 
  2. How and when do you use promises?
  3. How do you run Parallel promises?

What are Promises?


Promises in JavaScript, as the name suggests is a promise which assures you that it will give you the result of an Asynchronous operation. 

The result can only be of 2 types-

  1. Value
  2. Error
When you create a Promise object it is always in the 'Pending' state. After performing an Asynchronous operation, the promise can either be in 'Fulfilled' state which gives us the value, or 'Rejected' state, which gives us an error.


How and when do you use Promises?

The main function of promises is to solve the Callback Hell problem. When dealing with Multiple Asynchronous Operations, multiple callbacks makes the code very complex to understand causing the Callback Hell problem. So, promises reduce the amount of callbacks made by a large scale.

Here we will compare Asynchronous Code written with and without promises:


A little hard to understand right? Now I will write the same code using promises:


Using Promises we have reduced the Cognitive Complexity and solved the callback hell.
We can also write the reject condition result in the functions' Promise constructor to log an error to make our error handling easier or completely remove the reject parameter if we don't need it.

How and when do you run Parallel Promises?

Sometimes we need to execute a piece of code after all Asynchronous operations have been complete.(For example: Calling an API)
This is when we may need to run Parallel Promises. To do this we can use the .all method of the Promise class. It can take an array of promises and return a new Promise after all the promises in the array have been resolved.
The following is an example of Parallel Promises:


The result of the final promise will be an array of resolved promises from each Asynchronous operation in the array.
Alternatively, we can use the .race function of Promise class to get result of whichever Asynchronous promise gets resolved first.

Conclusion

Thank you for reading this far. I hope this gives you a basic understanding of how to use JavaScript Promises.
 

0 Comments