Promises are the ideal choice for handling asynchronous operations in the simplest manner.
A Promise has four states:
- fulfilled: Action related to the promise succeeded
- rejected: Action related to the promise failed
- pending: Promise is still pending i.e not fulfilled or rejected yet
- settled: Promise has fulfilled or rejected
A promise can be created using Promise constructor.
- Promise constructor takes only one argument a callback function.
- Callback function takes two arguments, resolve and reject
- Perform operations inside the callback function and if everything went well then call resolve.
- If desired operations do not go well then call reject.
Success, Welcome to Masai tribe
Promises can be consumed by registering functions using .then and .catch methods.
then() is invoked when a promise is either resolved or rejected.
then() method takes two functions as parameters.
catch() is invoked when a promise is either rejected or some error has occured in execution.
catch() method takes one function as parameter.
Below code snippet shows example
Benefits of Promises
- Improves Code Readability.
- Better handling of asynchronous operations.
- Better flow of control definition in asynchronous logic.
- Better Error Handling.