0

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?

  • 2
    *"...following this tutorial, this is the complete code from the tutorial:"* Then I strongly urge you to put it aside and find a different tutorial. That code is **really** poor on multiple levels. – T.J. Crowder Mar 25 '22 at 09:11
  • *"Why is `const attachResolveCallback` needed, instead of just using this keyword in the prototype function?"* `this` would mean something different there. Because `attachResolveCallback` is a traditional function, the value of `this` during a call to it is set by how the call is made. The way `then` makes the call in that code uses the default `this`, which is the global object in loose mode or `undefined` in strict mode (all new code should use strict mode). So that code would fail in strict mode. In loose mode, it sets `resolveCallback` as a **global**. – T.J. Crowder Mar 25 '22 at 09:15
  • But seriously, again, close the tab with that tutorial in it and never open it again. :-) – T.J. Crowder Mar 25 '22 at 09:16
  • 1
    @T.J.Crowder Oh so it's **global**! That makes more sense, yeah now it seems like that is indeed a poor tutotial :D Thanks a lot for the reply! – Nanyu Ding Mar 25 '22 at 09:20

0 Answers0