Promises are a fundamental concept in JavaScript, providing a way to handle asynchronous operations in a more manageable and readable way. They're crucial for modern JavaScript development, especially when dealing with tasks like fetching data from an API, reading files, or setting timers.
A Promise represents the eventual result of an asynchronous operation. It's either:
Promises have three possible states:
You can create Promises in several ways:
// Using the Promise constructor: const myPromise = new Promise((resolve, reject) => { // Code to perform the asynchronous operation setTimeout(() => { resolve("Data from the asynchronous operation"); // reject("An error occurred"); }, 1000); });
The `.then()` method is used to handle the fulfillment of a promise, and the `.catch()` method is used to handle rejections.
myPromise .then(data => { console.log("Resolved:", data); return "Processed Data"; }) .catch(error => { console.error("Rejected:", error); }) .finally(() => { console.log("Promise completed"); });
The finally
block executes regardless of whether the promise resolves or rejects.