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 promises// 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');
});