What Is Promise In Javascript
A promise is an object which represents the eventual completion or failure of an asynchronous operation. It is basically a returned object to which we attach callbacks, instead of passing callbacks into a function. Promises can be used to deal with asynchronous operations in JavaScript. They are preferred when dealing with multiple asynchronous operations where callbacks have the potential of creating callback hell leading to disturbing code. Before promises events and callback functions were in use but they had few functionalities and created unmanageable code. Many callback functions can create callback hell that leads to unmanageable code. And so, Events were not good at handling asynchronous operations.
Promises are the best choice for dealing with asynchronous operations in the most efficient and simplest manner. They can handle multiple asynchronous operations very easily and gives better error handling than callbacks or events. We can also say that promises are the ideal or the best choice for handling multiple callbacks at the same time, thus avoiding the undesired callback hell situation. Promises do provide a better scope for a user to read the code in a more efficient and effective manner especially if that particular code is used for implementing many or multiple asynchronous operations.
A promise mainly has three states:
- Resolved
- Pending
- Rejected
It can be constructed using a constructor,