In JavaScript, a Promise represents an asynchronous operation that can resolve or reject. You can create a custom Promise-like object using a constructor function and adding methods to its prototype.
1️⃣ Basic Custom Promise Implementation
function MyPromise(executor) {
let onResolve;
let onReject;
let fulfilled = false;
let rejected = false;
let value;
function resolve(val) {
fulfilled = true;
value = val;
if (onResolve) onResolve(val);
}
function reject(err) {
rejected = true;
value = err;
if (onReject) onReject(err);
}
this.then = function(callback) {
onResolve = callback;
if (fulfilled) onResolve(value);
return this; // for chaining
};
this.catch = function(callback) {
onReject = callback;
if (rejected) onReject(value);
return this;
};
executor(resolve, reject);
}
2️⃣ Usage Example
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve("Success!");
}, 1000);
});
promise
.then((res) => console.log(res)) // Logs "Success!" after 1 second
.catch((err) => console.error(err));
🔹 Explanation
- Executor Function
- Passed to
MyPromise, getsresolveandrejectfunctions.
- Passed to
- Prototype Methods
then()→ handles success callback.catch()→ handles error callback.
- State Handling
- Tracks if the promise is fulfilled or rejected to allow async resolution.
💡 In Short:
You can create a custom Promise by defining a constructor function, managing its state, and adding
then/catchmethods to the prototype for chaining asynchronous operations.
This is a simplified prototype; real Promises handle chaining, multiple .then calls, and async resolution more robustly.