JavaScript Promises are a fundamental concept for handling asynchronous operations. They allow you to write cleaner, more manageable code by encapsulating the success or failure of an operation and its resulting value.
📌 Key Concepts of Promises
- State: A Promise can be in one of three states: pending, fulfilled, or rejected.
- Executor: A function that takes
resolve
andreject
as arguments to determine the outcome. - Chaining: Use
.then()
for success and.catch()
for errors to create a sequence of operations. - Async/Await: A modern syntax for writing asynchronous code synchronously (learn more: /en/tutorials/async-await).
🚀 Example: Creating a Promise
const myPromise = new Promise((resolve, reject) => {
// Simulate an asynchronous task
setTimeout(() => {
resolve("Success!");
}, 1000);
});
myPromise
.then(value => console.log(value)) // Output: Success!
.catch(error => console.error(error));
⚠️ Error Handling
- Always use
.catch()
to handle errors in Promise chains. - Errors can be thrown explicitly with
throw new Error("Message")
.
📚 Expand Your Knowledge
- JavaScript Promises Deep Dive for advanced patterns.
- Promise vs Callback to compare with older methods.