The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Promise States
Pending: Initial state of a promise, neither fulfilled nor rejected.
Fulfilled: The operation completed successfully.
Rejected: The operation failed.
Creating Promises
/* [Imp..] The new keyword is used to create a new instance of an
object based on a constructor function */
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation
if (/* operation successful */) {
resolve(result);
} else {
reject(error);
}
});
Promise Methods:
1 . then(): Handles fulfillment of the promise.
myPromise.then(result => {
// Handle fulfillment
})
2 . catch(): Handles promise rejection.
myPromise.catch(error => {
// Handle rejection
});
3 . finally(): Executes after then()
or catch()
, regardless of the promise state.
myPromise.finally(() => {
// Cleanup
});
3 . Promise.race(): Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
Promise.all([promise1, promise2, promise3])
.then(results => {
// All promises fulfilled
}).catch(error => {
// At least one promise rejected
});
Chaining Promises
Promise chaining executes asynchronous operations sequentially with error handling.
promise1.then(result1 => {
// Process result1
return result2;
})
.catch(error => {
//Handle error for promise result 1 only
})
.then(result2 => {
// Process result2
})
.catch(error => {
// Handle any errors in the chain
});
Promises provide a powerful mechanism for handling asynchronous operations in JavaScript. Understanding these concepts will help you write cleaner and more efficient asynchronous code.