A JavaScript Promise is a built-in feature that represents the eventual completion (or failure) of an asynchronous operation. It provides a more structured and flexible way to work with asynchronous code compared to traditional callback functions.
Promises have three states:
Pending: The initial state when the promise is created, and the asynchronous operation is still ongoing.
Fulfilled: The state when the asynchronous operation is successfully completed, and a result value is available.
Rejected: The state when the asynchronous operation encounters an error or fails, and an error reason is provided.
Here's a simple example of using a Promise in JavaScript:
const myPromise = new Promise((resolve, reject) => {
// Simulate an asynchronous operation (e.g., fetching data from a server)
setTimeout(() => {
const success = true; // You can replace this with your actual logic
if (success) {
resolve("Operation succeeded!"); // Resolve the promise with a value
} else {
reject("Operation failed!"); // Reject the promise with an error
}
}, 2000); // Simulating a delay of 2 seconds
});
// Using the promise
myPromise
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});
In this example, the Promise is created with a function that takes two arguments:
resolve and reject. Inside this function, you perform your asynchronous operation and call
resolve when it succeeds or reject when it fails.
You can then use .then() to handle the successful outcome and
.catch() to handle errors. Promises make it easier to write and reason about asynchronous code, especially when dealing with complex chains of asynchronous operations.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
A JavaScript Promise is a built-in feature that represents the eventual completion (or failure) of an asynchronous operation. It provides a more structured and flexible way to work with asynchronous code compared to traditional callback functions.
Promises have three states:
Here's a simple example of using a Promise in JavaScript:
In this example, the Promise is created with a function that takes two arguments: resolve and reject. Inside this function, you perform your asynchronous operation and call resolve when it succeeds or reject when it fails.
You can then use .then() to handle the successful outcome and .catch() to handle errors. Promises make it easier to write and reason about asynchronous code, especially when dealing with complex chains of asynchronous operations.