将promise处理函数绑定到对象

San*_*ria 18 javascript promise

我有一些代码:

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

如何在上下文中将failure函数绑定到this对象bar.我知道我将不得不使用myFunc.bind(this)但我可以替代什么myFunc

rob*_*lep 42

你可以bind像这样使用:

var bar = foo().then(function success(value) {
  // compute something from a value...
}, function failure(reason) {
  // handle an error...
}.bind(this));
Run Code Online (Sandbox Code Playgroud)


IMS*_*SoP 6

您目前有一个匿名(虽然已标记)函数用于您的故障回调:

function failure(reason) {
   // handle an error...
}
Run Code Online (Sandbox Code Playgroud)

正如robertklep所说,你可以立即打电话.bind给那个匿名函数.但是,使用命名函数可能更具可读性,并将其.then()作为变量传递:

function success(value) {
    // compute something from a value...
}
function failure(reason) {
    // handle an error...
}
var bar = foo().then(success, failure.bind(this));
Run Code Online (Sandbox Code Playgroud)


Fel*_*lix 5

如果您只对封闭范围的对象感兴趣this,并且您使用的是 ECMA6 或更高版本,则可以使用箭头函数。它看起来像:

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

您可以在MSD 使用承诺中找到更多示例