Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a promise handler function to an object

I have some code like:

var bar = foo().then(function success(value) {
  // compute something from a value...
}, function failure(reason) {
  // handle an error...
});

How do I bind the failure function to the this object in the context of bar. I know I will have to use myFunc.bind(this) but what do I substitute in place of myFunc?

like image 760
Sankha Narayan Guria Avatar asked May 08 '13 07:05

Sankha Narayan Guria


3 Answers

You can use bind like this:

var bar = foo().then(function success(value) {   // compute something from a value... }, function failure(reason) {   // handle an error... }.bind(this)); 
like image 81
robertklep Avatar answered Sep 22 '22 13:09

robertklep


You currently have an anonymous (although labelled) function for your failure callback:

function failure(reason) {    // handle an error... } 

As robertklep says, you can immediately call .bind on that anonymous function. However, it might be more readable to use a named function instead, and pass it into .then() as a variable:

function success(value) {     // compute something from a value... } function failure(reason) {     // handle an error... } var bar = foo().then(success, failure.bind(this)); 
like image 24
IMSoP Avatar answered Sep 25 '22 13:09

IMSoP


If you are only interested in the object this of the enclosing scope, and you are using ECMA6 or later, you could use arrow functions. It would look like:

var that = this;
var bar = foo().then(value => {
  // compute something from a value...
  console.log(this === that); // true
  this.propA = value.propA
});

You could find more examples in MSD Using promises

like image 44
Felix Avatar answered Sep 24 '22 13:09

Felix