Promise and Methods
A promise is used to perform asynchronous tasks in JavaScript because JavaScript is a single-threaded programming language.
Three possible states in Promise
- Pending: The task is still in progress.
- Fulfilled: The task completed successfully.
- Rejected: The task failed.
Example of promise
Methods of Promise
- Promise.all()
- Promise.any()
- Promise.race()
- Promise.finally()
- Promise.allsettled()
- Promise.catch()
- Promise.reject()
- Promise.resolve()
Promise.catch()
This method runs once all promises are completed, whether they are resolved or rejected. It is used to handle errors if any occur.
Promise.reject()
This method is used to reject the promise if it fails or encounters an error.
Promise.resolve()
This method is used to indicate that if the promise is successful, it will be in the resolved state.
Promise.all()
It is a function used to handle multiple asynchronous operation concurrently. It take an array of promises and return a single promise that resolves when all promises in array have resolves or reject if any promises in the array rejects.
Promise.any()
It an array of promises and returns the first fulfilled promise. If no promise is fulfilled, it rejects with an error
, which wraps multiple errors into a single error.
Promise.finally()
When a promise is completed, either resolved or rejected, the specified callback function is executed. This helps avoid duplicating code in both the promise’s then() and catch() handlers.
Promise.race()
This method returns a promise that resolves or rejects as soon as one of the promises in an iterable (such as an array) fulfills or rejects, with the corresponding value or reason.
Promise.allsettled()
This method takes an array of promises, waits for all of them to complete (whether resolved or rejected), and returns a promise.
Need for Promise:
If a function is waiting for a resource or performing a network request, this takes time. Meanwhile, the entire execution freezes. This is where asynchronous programming comes into play with the help of features like callbacks, promises, and async/await. These features allow us to perform time-consuming actions without affecting the main execution thread.