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?
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));
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));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With