rabbitco rabbitco - 6 months ago 8
Javascript Question

Is it possible to set the value of `this` inside a promise executor function?

Is it possible in this code:

var this_module = {

foo: 'something'

promise: new Promise (function(resolve, reject) {

resolve (this.foo);
})
}


to set the value of
this
to be
this_module
so that
this.foo
will be
foo: 'something'
?

Answer

You need to use the getter syntax:

var this_module = {

    foo: 'something'

    get promise() {
       return new Promise (function(resolve, reject) {
          resolve (this.foo);
       }.bind(this))
    }
}

It happens because you don't have the object itself initialized when adding the property to it promise: new Promise().
In a getter, the object is initialized already and the callback can be bind with this object (see more about .bind()).

Note: This will return a new promise every time the property is accessed (thanks @Felix).

Comments