Promises represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They provide a cleaner alternative to callbacks for managing async code.

💡 Core Concept
A Promise is an object that may be pending, fulfilled, or rejected. You attach handlers to handle success or failure once the async operation completes.
Creating a Promise
A Promise is created with a function that receives two callbacks: resolve and reject. Call resolve when your async task succeeds, reject if it fails.
📌 Deep Dive: Basic Promise Creation
const myPromise = new Promise((resolve, reject) => {
const success = true; // simulate a condition
if (success) {
resolve('Operation succeeded');
} else {
reject('Operation failed');
}
});
Consuming Promises
Use .then() to handle success, and .catch() to handle errors.
📌 Deep Dive: Handling Promise Results
myPromise
.then(result => {
console.log(result); // "Operation succeeded"
})
.catch(error => {
console.error(error);
});
Promise States
| State | Description |
|---|---|
| Pending | Initial state; neither fulfilled nor rejected. |
| Fulfilled | Operation completed successfully. |
| Rejected | Operation failed. |
Chaining Promises
Promises can be chained to perform sequential asynchronous operations.
📌 Deep Dive: Promise Chaining
new Promise((resolve) => resolve(2))
.then(value => value * 3)
.then(value => {
console.log(value); // 6
});
⚠️ Important
Always provide a .catch() handler to catch possible rejections and avoid unhandled promise rejections.
Promise Utility Methods
Promise.resolve(value): Returns a Promise resolved withvalue.Promise.reject(error): Returns a Promise rejected witherror.Promise.all(iterable): Waits for all Promises to fulfill or any to reject.Promise.race(iterable): Resolves or rejects as soon as any Promise resolves or rejects.
📌 Deep Dive: Using Promise.all
Promise.all([
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3)
]).then(results => {
console.log(results); // [1, 2, 3]
});
💡 Summary
- Promises simplify async code handling.
- Use
new Promiseto create promises. - Attach
.then()and.catch()for success and error handling. - Chain promises for sequential async operations.
- Utility methods help coordinate multiple promises.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which Promise state indicates the asynchronous operation completed successfully?
Question 2 of 2
What method is used to handle errors from a Promise?
Loading results...