Learn the concept
Promises & Async/Await
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, or rejected, and provides .then(), .catch(), and .finally() methods for handling results.
Promises provide a cleaner way to handle asynchronous operations compared to callbacks.
Promise States:
Key Methods:
.then(onFulfilled, onRejected): Handles success and optionally errors.catch(onRejected): Handles errors (syntactic sugar for .then(null, fn)).finally(onFinally): Runs regardless of outcomeStatic Methods:
Promise.all(): Waits for all promises, fails if any failsPromise.allSettled(): Waits for all, returns all results regardless of outcomePromise.race(): Returns first settled promisePromise.any(): Returns first fulfilled promisePromise.resolve() / Promise.reject(): Create resolved/rejected promisesPromise.withResolvers() (ES2024): Returns {promise, resolve, reject} for deferred patternsPromise.try() (ES2025): Wraps sync or async functions into a Promise chain safely// Creating a Promise
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true;
if (success) {
resolve({ data: 'Hello World' });
} else {
reject(new Error('Failed to fetch'));
}
}, 1000);
});
// Consuming a Promise
fetchData
.then(result => {
console.log(result.data); // 'Hello World'
return result.data.toUpperCase();
})
.then(upperData => {
console.log(upperData); // 'HELLO WORLD'
})
.catch(error => {
console.error(error.message);
})
.finally(() => {
console.log('Operation complete');
});Chaining HTTP requests with error handling using .then()/.catch() for sequential or parallel data loading
Tracking upload progress and handling success or failure asynchronously with user feedback
Sequencing queries that depend on previous results, such as fetching a user then their posts
Build a retry wrapper that attempts a failing async operation N times with exponential backoff delay
Fetch multiple API endpoints in parallel using Promise.all with loading and error states for each
HTTP client returning Promises with interceptors for request/response transformation and error handling