Binding a promise handler function to an object
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));