What is a JavaScript Promise?
In JavaScript, a promise is an object that represents the eventual completion or failure of an asynchronous operation. Promises are a key feature in modern web development, aiding in the management of asynchronous actions. They provide a cleaner alternative to the traditional callback-based approach.
Promise States
- Pending: The initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully, and the promise has a resultant value.
- Rejected: The operation failed, and the promise has a reason for the failure (an error).
Creating a Promise
A promise is created using the Promise
constructor, which takes a single function as an argument. This function, known as the executor, receives two parameters: resolve
and reject
.
const myPromise = new Promise((resolve, reject) => {
// Async operation here
if (/* success condition */) {
resolve('Success!');
} else {
reject('Failure!');
}
});
Using Promises
Once a promise is created, you can use the .then()
method to handle success and .catch()
to handle failure. For example:
myPromise
.then(result => console.log(result))
.catch(error => console.error(error));
In summary, JavaScript promises significantly enhance asynchronous programming, making code easier to read and maintain.