Promises and types with examples in details
Promises in JavaScript: An Overview
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises are used to handle asynchronous operations more effectively, enabling cleaner and more manageable code compared to traditional callback-based approaches.
States of a Promise
A Promise can be in one of three states:
- Pending: The initial state; the operation is still in progress.
- Fulfilled: The operation completed successfully, and the promise has a result.
- Rejected: The operation failed, and the promise has a reason (typically an error).
Promise Syntax
In this example:
- The promise is created using the
new Promise()
constructor. - The
resolve
function is called when the asynchronous operation is successful. - The
reject
function is called if there is an error.
Handling Promises with .then()
, .catch()
, and .finally()
.then(onFulfilled, onRejected)
: This method is used to handle the fulfilled state of a promise. You can also handle rejection by passing an error handler..catch(onRejected)
: This method is used to handle the rejected state of a promise..finally(onFinally)
: This method runs no matter what (whether the promise is fulfilled or rejected).
Example: Using .then()
, .catch()
, and .finally()
Types of Promises
JavaScript offers a variety of ways to work with Promises, some of the commonly used types and patterns are as follows:
1. Simple Promise Example
A basic example to demonstrate how to create a Promise, resolve it, and handle its result:
2. Promise.all()
Promise.all()
takes an array of promises and returns a single promise that resolves when all the promises have been fulfilled. If any of the promises reject, the entire Promise.all()
will reject.
Example:
Key Points:
Promise.all()
returns a single promise that resolves when all the promises in the array are fulfilled.- If any of the promises reject,
Promise.all()
rejects immediately with the reason of the first promise that rejects.
3. Promise.race()
Promise.race()
takes an array of promises and returns a single promise that resolves or rejects as soon as one of the promises in the array resolves or rejects. Whichever promise is fulfilled or rejected first, the result is passed forward.
Example:
Key Points:
Promise.race()
resolves or rejects based on the first promise to resolve or reject in the array.
4. Promise.allSettled()
Promise.allSettled()
returns a promise that resolves once all promises have settled (either fulfilled or rejected), and it provides the outcome of each promise.
Example:
Key Points:
- Unlike
Promise.all()
,Promise.allSettled()
doesn't short-circuit if a promise rejects. - It always resolves once all promises have settled, returning an array of objects with each promise's status and result.
5. Promise.any()
Promise.any()
returns a promise that resolves as soon as any of the promises in the array resolves. If all promises reject, it will reject with an AggregateError
.
Example:
Key Points:
Promise.any()
resolves as soon as any promise in the array fulfills, and it rejects only if all promises reject.- The rejection reason will be an
AggregateError
when all promises fail.
6. Chaining Promises
One of the core features of promises is the ability to chain multiple .then()
calls. Each .then()
returns a new promise, allowing for asynchronous operations to be performed sequentially.
Example:
Key Points:
- Each
.then()
handles the resolved value from the previous.then()
and can return a new value or another promise. .catch()
can be used at the end of a chain to catch any errors that occur anywhere in the chain.
7. Handling Async Functions with Promises
JavaScript’s async
/await
syntax allows working with promises in a more synchronous-like manner. The await
keyword can be used to wait for a promise to resolve, making it easier to write asynchronous code without using .then()
and .catch()
.
Example:
Key Points:
async
functions always return a promise, andawait
is used to wait for the promise to resolve.- Errors can be caught using
try
/catch
blocks insideasync
functions.
Conclusion:
- Promises in JavaScript help handle asynchronous operations in a more manageable way than using callbacks.
- Types of Promises like
Promise.all()
,Promise.race()
,Promise.allSettled()
, andPromise.any()
offer different ways to handle multiple promises simultaneously, each suited to different use cases. - Chaining promises allows asynchronous operations to be performed in a sequence, while
async
/await
syntax simplifies handling promises in a more synchronous style.
By understanding these types of promises and their behaviors, you can efficiently handle asynchronous logic in JavaScript applications.
Comments
Post a Comment