Binding a promise handler function to an object

后端 未结 4 1003
迷失自我
迷失自我 2020-12-18 19:21

I have some code like:

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


        
4条回答
  •  眼角桃花
    2020-12-18 19:40

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

    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

提交回复
热议问题