I tried to recreate javascript promise, following this tutorial, this is the complete code from the tutorial:
function myPromise(callback) {
let resolve = function(value){
this.resolveCallback(value);
}
callback(resolve)
}
// .then
myPromise.prototype.then = function(resolveCallback){
attachResolveCallback(resolveCallback);
}
const attachResolveCallback = function(resolveCallback){
this.resolveCallback = resolveCallback;
}
im confused about the part that implements .then():
// .then
myPromise.prototype.then = function(resolveCallback){
attachResolveCallback(resolveCallback);
}
const attachResolveCallback = function(resolveCallback){
this.resolveCallback = resolveCallback;
}
Why is const attachResolveCallback needed, instead of just using this keyword in the prototype function?
So I replaced the .then part of the code with:
myPromise.prototype.then = function(resolveCallback){
this.resolveCallback = resolveCallback;
}
But the code does not work and returns an error:
promise.js:4 Uncaught TypeError: this.resolveCallback is not a function
at resolve (promise.js:4:14)
at promise.js:25:9
I suspect this problem is due to usage of 'this' when assigning properties to functions, but im not sure about the specific reason here. Could someone enlighten me on this problem?