I'm currently working on developing my own Promise in JavaScript to enhance my comprehension of how Promises work. I've encountered a roadblock while trying to understand the .then method and I need some guidance: I came across the documentation for the .then method here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then, which mentions that the .then method returns a Promise. However, I'm struggling with writing this because it appears that this.result is undefined. Could someone please explain why this is happening and how I can resolve this issue?
Below is the code I'm working with:
class LitePromise {
constructor(fn) {
if (typeof fn !== "function") {
throw new TypeError("Promises must be functions");
}
this.fn = fn;
this.state = PENDING;
this.result = null;
const resolveCallback = this.resolve.bind(this);
const rejectCallback = this.reject.bind(this);
try {
fn(resolveCallback, rejectCallback);
} catch (err) {
this.reject(err);
}
}
resolve(arg) {
console.log(arg, "arg");
this.result = arg;
this.state = RESOLVED;
}
reject() {
this.state = REJECTED;
}
// create an instance of this promise
then(callback) {
const tinyPromise = new LitePromise(this.fn);
console.log(callback, "callback");
try {
return tinyPromise.resolve(callback(this.result));
} catch {
return tinyPromise.reject(callback(this.result));
}
}
}
console.log("------------------");
const yaypromise = new LitePromise((resolve, reject) => {
console.log("1. running");
setTimeout(() => {
console.log("2. resolving");
resolve("yay");
}, 100);
}).then((result) => {
console.log("3. evaluating");
if (result !== "yay") {
console.log("It's not working yet");
return;
}
console.log("SUCCESS!", result);
});