Javascript: Promises + this

Consider the following code:

foo: function() { var self = this; var p1 = p2 = someFunctionThatReturnsAPromise(); Promise.all([p1, p2]) .then(self.bar); } bar: function(promises) { var self = this; console.log(self); } 

Output:

 undefined 

But if I do the following:

 foo: function() { var self = this; var p1 = p2 = someFunctionThatReturnsAPromise(); Promise.all([p1, p2]) .then(function(result) { self.bar(result); }); } bar: function(promises) { var self = this; console.log(self); } 

Output:

 { foo: [Function], bar: [Function] } 

I don’t understand why the first call changes where this one indicates the function of the bar. Can someone enlighten me?

+5
source share
1 answer

When you pass self.bar to the then method, you pass a reference to the function. Although it looks like you are also specifying that it should be called on a self object, this is actually not what happens. The self object is not included in this function. The value of the this object is determined when the function is called, and not when it is defined or passed as an argument.

In your second example, self is the this object in the context of the function, because here you are calling the function.

Another way to make it work is to make the this object always be self , overriding the behavior described above. You can achieve this with .bind() :

 Promise.all([p1, p2]) .then(self.bar.bind(self)); 
+3
source

All Articles