javascript 将承诺处理函数绑定到对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16435167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:40:24  来源:igfitidea点击:

Binding a promise handler function to an object

javascriptpromise

提问by Sankha Narayan Guria

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 failurefunction to the thisobject in the context of bar. I know I will have to use myFunc.bind(this)but what do I substitute in place of myFunc?

我如何绑定failure功能将this在上下文对象bar。我知道我将不得不使用myFunc.bind(this)但我用什么代替myFunc

回答by robertklep

You can use bindlike this:

你可以这样使用bind

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

回答by IMSoP

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 .bindon that anonymous function. However, it might be more readable to use a named function instead, and pass it into .then()as a variable:

正如 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));

回答by Felix

If you are only interested in the object thisof the enclosing scope, and you are using ECMA6 or later, you could use arrow functions. It would look like:

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

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

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

回答by Pawe?

What I found very useful is to bind each then()'s [function] handler to the one empty object, so each function could have the access to it. Then the user can set and get the properties in each Promise by thiskeyword. The unit test frameworks works similarly.

我发现非常有用的是将 eachthen()的 [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);
    }