Promises are a core concept in JavaScript that allows you to handle asynchronous operations in a more manageable way. They are used extensively in modern JavaScript applications to simplify the handling of asynchronous code.
What is a Promise?
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
- Pending: The initial state of a promise, indicating that the operation has not completed yet.
- Fulfilled: The state of a promise when the operation has completed successfully.
- Rejected: The state of a promise when the operation has failed.
Basic Usage
Here's a simple example of how a promise works:
let promise = new Promise((resolve, reject) => {
// Simulate an asynchronous operation
setTimeout(() => {
if (/* operation was successful */) {
resolve('Operation completed successfully');
} else {
reject('Operation failed');
}
}, 1000);
});
promise
.then((message) => {
console.log(message);
})
.catch((error) => {
console.error(error);
});
Chaining Promises
You can chain promises together using the .then()
and .catch()
methods. This allows you to perform multiple asynchronous operations in sequence.
let promise1 = new Promise((resolve, reject) => {
// ...
});
let promise2 = promise1.then((result) => {
// ...
});
promise2.then((result) => {
// ...
}).catch((error) => {
// ...
});
Error Handling
Promises provide a convenient way to handle errors using the .catch()
method.
let promise = new Promise((resolve, reject) => {
// ...
});
promise.then((result) => {
// ...
}).catch((error) => {
console.error('An error occurred:', error);
});
More Resources
For a deeper understanding of promises, you might want to read this comprehensive guide on MDN.
Promise Diagram