In JavaScript, a Promise is a built-in object used to handle asynchronous operations. It represents a value that may be available now, or in the future, or never. Promises help manage asynchronous code in a more readable and maintainable way compared to callbacks.
Key Features of a Promise:
States:
- Pending: The initial state, neither fulfilled nor rejected.
- Fulfilled: The operation was completed successfully.
- Rejected: The operation failed.
Methods:
.then(onFulfilled, onRejected): Attaches callbacks for when the promise is fulfilled or rejected..catch(onRejected): Attaches a callback for when the promise is rejected..finally(onFinally): Attaches a callback to be executed regardless of the promise's outcome.
Creating a Promise: A promise is created using the
Promiseconstructor, which takes a function with two parameters:resolveandreject.
Example 1: Basic Promise
Example 2: Simulating an Asynchronous Operation
Example 3: Chaining Promises
Example 4: Using Promise.all
When you need to wait for multiple promises to resolve:
Benefits of Promises:
- Avoids callback hell (nested callbacks).
- Improves readability and maintainability.
- Works well with modern async/await syntax for even cleaner asynchronous code.
Would you like to learn about async/await, or do you have a specific use case in mind?
Comments
Post a Comment