将promise处理函数绑定到对象

时间:2013-05-08 07:37:52

标签: javascript promise

我有一些代码:

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

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

4 个答案:

答案 0 :(得分:40)

您可以像这样使用bind

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

答案 1 :(得分: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));

答案 2 :(得分:1)

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

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

中找到更多示例

答案 3 :(得分:0)

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

    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);
    }