0

I am new to promises but my understanding was that the arguments to .then() were 2 functions (optionally) to handle onfulfilled and onreject. These functions can return a value, a promise or throw an error.

I have also seen examples where the fulfillment functions are functions defined elsewhere such as:

function onFulfill(){...}
promise.then(onFulfill)

I am attempting to have a custom object which has some functions which can be these onFulfill etc functions see the example below.

function Test() {
    this.value = "something"
}

Test.prototype.makePromise = function() {
    console.log(this)
    return Promise.resolve();
};

Test.prototype.test = function() {
    console.log(this)
};

var T = new Test();

T.test()

var P = Promise.resolve().then(T.makePromise)

My problem arises because when I call T.test() the printed "this" is as expected. But when I pass the T.makePromise to the .then() function it prints out the global object as "this" and I don't understand why this would be the case.

I know I can get it to work by doing something like:

var P = Promise.resolve().then(()=>{return T.makePromise()})

But I don't understand why I should have to do that.

Thank you. I'm sorry if this is a terribly basic question. Also not that I think this matters but I am using this from node.

3 Answers3

2

Since you are passing the function reference, it loses its connection to the object T. You are not passing T + makePromise, but makePromise as if it was a standalone function. Thus T cannot be this any more in the calling context.

Just write it that way:

const P = Promise.resolve().then(() => T.makePromise())

Now, when calling makePromise, T is available on the scope and automatically bound to this.

ideaboxer
  • 3,863
  • 8
  • 43
  • 62
1

You could try something like

var P = Promise.resolve().then(T.makePromise.bind(T))
Glia
  • 371
  • 2
  • 9
1

This is mostly a question about this. Because the then function is what is invoking the calling of T.makePromise, the call site is no longer the context of Test but is the global context.

this is a reflection of whatever the context is that invoked the function using this. Once you pass that off to async land, you don't have control over what this will be unless you bind it before-hand.

DillGromble
  • 383
  • 2
  • 8