Introduction to Promises
JavaScript promises provide a powerful way to handle asynchronous operations. A promise represents a value that may be available now, in the future, or never. Promises are useful for better handling of callbacks and provide a cleaner, more readable approach to managing asynchronous code.
Why Use Promises?
Promises simplify handling asynchronous code in a more predictable manner. They help in avoiding "callback hell" and make code easier to manage, especially when dealing with multiple asynchronous operations.
States of a Promise
- Pending: Initial state, neither fulfilled nor rejected.
- Fulfilled: The operation was completed successfully.
- Rejected: The operation failed.
Using Promises
let promise = new Promise(function(resolve, reject) {
// asynchronous operation
let success = true;
if (success) {
resolve("The operation was successful!");
} else {
reject("The operation failed.");
}
});
promise.then(function(result) {
console.log(result); // The operation was successful!
}).catch(function(error) {
console.log(error); // The operation failed.
});