21

我有一些代码,例如:

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

如何将failure函数绑定thisbar. 我知道我将不得不使用myFunc.bind(this),但我可以用什么代替myFunc

4

4 回答 4

52

你可以bind这样使用:

var bar = foo().then(function success(value) {
  // compute something from a value...
}, function failure(reason) {
  // handle an error...
}.bind(this));
于 2013-05-08T08:19:47.640 回答
6

您当前有一个用于失败回调的匿名(尽管已标记)函数:

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

正如 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));
于 2013-05-08T08:26:58.450 回答
4

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

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

您可以在MSD Using promises中找到更多示例

于 2019-04-23T14:26:53.570 回答
0

我发现非常有用的是将 eachthen()的 [function] 处理程序绑定到一个空对象,这样每个函数都可以访问它。然后用户可以通过关键字设置和获取每个 Promise 中的属性this。单元测试框架的工作方式类似。

    chainPromiseList([getName,getAge],finalDone,rejectHandle);

    function chainPromiseList(promiseList,finalDone,errHandle){
      var userContext = new UserContext();
      if(typeof finalDone==='function') promiseList.push(finalDone);
      if(typeof errHandle==='function') promiseList.push(errHandle);
      return promiseList.reduce((total,curVal,curInd,arr)=>{
        var last = curInd+1===arr.length;
        var method = last&&typeof errHandle==='function' ? 'catch':'then';
        var concatenated = total[method](curVal.bind(userContext));
        return concatenated;
      },Promise.resolve());
        function UserContext(){};
    }
    
    function getName(){
      return new Promise((resolve,reject)=>{
        setTimeout(()=>{
          console.log('got name!');
          this.name = 'Paul';
          resolve();
        },500);
      });
    }

    function getAge(){
      return new Promise((resolve,reject)=>{
        setTimeout(()=>{
          console.log('got age!');
          this.age = 26;
          resolve();
        },500);
      });
    }

    function finalDone(){
      console.log(`Hello, I'm ${this.name} and I'm ${this.age}yo.`);
    }

    function rejectHandle(msg){
      console.log('Error: ',msg);
    }

于 2017-09-03T07:05:45.560 回答