Implement a Custom Promise Class
You are required to implement a custom Promise.
Promise is an object that represent the eventual completion or failure of an asynchronous operation. Promise can be in 3 states:
Pending: The initial state, neither fulfilled nor rejected.Fulfilled: The operation completed successfully.Rejected: The operation failed
Example
let promise = new Promise((resolve, reject) => {
// Asynchronous operation
let success = true; // Assume the operation succeeds
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
});
// Example of Usage
promise
.then((result) => {
console.log(result); // "Operation successful!"
})
.catch((error) => {
console.error(error); // "Operation failed!"
})
.finally(() => {
console.log("Operation completed."); // This runs no matter what
});