Promises in javascript

Promises in javascript

Hey everyone! let's learn about JS Promises: The right way!

What is a promise in javascript?

It's an eventual completion or failure of an asynchronous operation. A promise in javascript is similar to our real-life promise, suppose I make a promise to my nephew that I will give him chocolates when I will return from the shop. Now it would have 3 results either the promise will be fulfilled means succeeded, rejected i.e, failed, or it will be pending means not fulfilled or rejected yet! likewise, the promise has 3 states in javascript :

Fulfilled : promise succeeded.

Rejected : promise failed.

Pending: promise not fulfilled or rejected yet.

promises.png

For example, if you want to request the data from the server you need to use Fetch() method that returns a promise. The fetch () method has a default 'GET' request, you can also send data to the server using a 'POST' request. once you make a request to the server and until you receive data, your promise will be in a pending state i.e., neither you got data, nor the promise is rejected! When you successfully achieve to get the information from the server then your promise will be resolved! it will be successful. if you don't get any data from the server, then your promise is rejected or failed! once your promise is resolved you can convert that received data into JSON() and use it as per your need.

This is how promises in javascript work! either it will be fulfilled, rejected, or pending and if gets rejected because of some error then you can use the .catch() method to catch the error and show it to the user.

Why do we use promises in javascript?

What are Synchronous and Asynchronous operations in javascript?

Synchronous operations mean to be in a sequence. The code will be executed in a sequence means one by one. basically, every statement has to wait for the earlier statement to get executed and in Asynchronous operations, the program would be executed immediately. It will not wait for the earlier statement like synchronous operations do.

1) Promises are used to handle Asynchronous operations in javascript.

2) Promises are easy to manage when dealing with multiple asynchronous operations whereas when using callbacks, it would get really difficult to manage code.

3) before promises, events, and callback functions were used but they had limited functionalities, and the code used to get difficult to manage.

4) Using promises, we can handle errors easily and better than events and callback functions.