In JavaScript, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It helps manage asynchronous operations more effectively than traditional callback functions.
Promises address some of the limitations of callbacks and events in managing asynchronous operations. Unlike callbacks, Promises offer a more structured approach to handling asynchronous code and avoid common issues such as callback hell.
• Pending: The initial state of a promise. The promise is neither fulfilled nor rejected.
• Fulfilled: The state when the asynchronous operation completes successfully.
• Rejected: The state when the asynchronous operation fails.
• Settled: The state when the promise has either been fulfilled or rejected.
1. Single Completion: A Promise can only succeed or fail once.
2. Immutability: Once a Promise is fulfilled or rejected, it cannot change its state.
Returns a Promise that is resolved with the given value.
If the value is already a Promise, it returns that Promise.
Returns a Promise that is rejected with the given reason.
Returns a Promise that resolves when all Promises in the iterable argument have resolved, or rejects with the reason of the first promise that rejects.
Returns a Promise that resolves or rejects as soon as one of the Promises in the iterable resolves or rejects, with the value or reason from that Promise.
Returns a Promise that resolves when any of the Promises in the iterable resolves, or rejects if no Promise in the iterable resolves.
Adds a handler to be called when the Promise is settled, regardless of its outcome.
new Promise(function(resolve, reject) {
// Asynchronous code here
if (/* operation successful */) {
resolve(result); // Resolves the promise with the result
} else {
reject(error); // Rejects the promise with the error
}
});
• resolve(value): The function to call when the operation completes successfully.
• reject(reason): The function to call when the operation fails.
1. Improved Readability: Promises avoid nested callbacks and improve code readability.
2. Better Error Handling: Promises provide a clear and consistent way to handle errors with .catch().
<script>
var p = new Promise(function(resolve, reject) {
var x = 5;
if (x == 4)
resolve(" executed and resolved successfully");
else
reject("rejected");
});
p.then(function(fromResolve) {
document.write("Promise is " + fromResolve);
}).catch(function(fromReject) {
document.write("Promise is " + fromReject);
});
</script>
Promise is rejected