JavaScript promises are a feature in the language used to handle asynchronous operations more effectively and avoid callback hell (nested callbacks). A promise represents a value that may be available now, in the future, or never. It acts as a placeholder for a result that will be returned later, allowing you to write cleaner and more manageable asynchronous code.
States of a Promise
1. Pending: The initial state; the promise is neither fulfilled nor rejected.
2. Fulfilled: The operation is completed successfully, and the promise has a resulting value.
3. Rejected: The operation failed, and the promise has a reason for the failure (an error).
Using Promises
A promise is created using the Promise
constructor:
let promise = new Promise((resolve, reject) => {
// Perform an operation
let success = true; // Example condition
if (success) {
resolve("Operation was successful!");
} else {
reject("Operation failed.");
}
});
You can handle the resolved or rejected outcomes using .then()
and .catch()
:
promise.then((result) => {
console.log(result); // "Operation was successful!"
}).catch((error) => {
console.error(error); // "Operation failed."
});
Chaining Promises
Promises can be chained to handle sequences of asynchronous operations:
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Error:", error));