In JavaScript, a promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. It's a way to handle asynchronous operations more easily and avoid the complexities of callback-based approaches.
A promise can be in one of three states:
- Pending: Initial state, representing that the operation hasn’t completed yet.
- Fulfilled: The operation completed successfully, and the promise now has a resolved value.
- Rejected: The operation failed, and the promise has a reason for the failure.
Here's a basic example of creating and using a promise:
// Creating a promise
let myPromise = new Promise((resolve, reject) => {
// Asynchronous operation (e.g., fetching data)
let operationCompletedSuccessfully = true; // Change to false to see rejection
if (operationCompletedSuccessfully) {
// If successful, resolve with a value
resolve("Operation completed successfully!");
} else {
// If failed, reject with a reason
reject("Operation failed!");
}
});
// Using the promise
myPromise
.then((result) => {
// If the promise is resolved
console.log("Success:", result);
})
.catch((error) => {
// If the promise is rejected
console.log("Error:", error);
});
Here's a breakdown:
-
A promise is created with the
new Promise()
constructor, which takes a callback function with two parameters:resolve and reject
. Inside this callback, you perform the asynchronous operation. -
If the operation succeeds, you call
resolve()
and pass the result. If it fails, you callreject()
and pass an error. -
To handle the result of the promise, you use the
.then()
method. If the promise is fulfilled, the success handler (passed to.then()
) will be executed. -
To handle errors or rejections, you use the
.catch()
method. This catches any errors that occur during the promise execution.
Promises provide a cleaner way to work with asynchronous code compared to nested callbacks. They also support chaining multiple asynchronous operations sequentially using .then()
and handling errors using .catch()
, making the code more readable and maintainable.