![JavaScript](/sites/default/files/faq/javascript.png)
In JavaScript, a promise is an object that represents the eventual completion or failure of an asynchronous operation, and its resulting value. It allows you to handle asynchronous operations more easily by providing a way to deal with their eventual success or failure, without getting trapped in callback hell (nested callbacks).
A promise can be in one of three states:
- Pending: Initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully, and the promise has a value.
- Rejected: The operation failed, and the promise has a reason for the failure.
Promises have methods such as `then()`
and `catch()`
which allow you to attach callbacks to handle the fulfillment or rejection of the promise. Here's a basic example:
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation, e.g., fetching data from a server
setTimeout(() => {
const success = true;
if (success) {
resolve("Operation succeeded!"); // Resolve the promise with a value
} else {
reject("Operation failed!"); // Reject the promise with a reason
}
}, 2000);
});
myPromise.then((value) => {
console.log(value); // Output: Operation succeeded!
}).catch((reason) => {
console.error(reason); // Output: Operation failed!
});
Promises are especially useful when working with asynchronous functions like fetching data from a server, reading files, or handling timeouts. They simplify the asynchronous code structure, making it more readable and manageable. Additionally, promises can be chained together using then() to perform multiple asynchronous operations sequentially.