【问题标题】:Chaining promises in class [duplicate]在类中链接承诺[重复]
【发布时间】:2019-07-29 20:53:06
【问题描述】:

我有一堂课,我试图像这样链接承诺:

class Parent {
  constructor() {
    this.driver = []
  }
  test() {
    this.method1()
    .then(this.method2)
    .then(() => {
      console.log('all done', this.driver)
    })
    .catch(err => {
      console.log('Something went wrong', err);
    });
  }
  method1() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        this.driver.push('0');
        resolve();
      },200)
    });
  }
  method2() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        this.driver.push('1');
        resolve();
      },200)
    });
  }
}

let instance = new Parent();
instance.test();

method2 导致错误

未捕获的类型错误:无法读取未定义的属性“驱动程序”

【问题讨论】:

    标签: javascript class promise


    【解决方案1】:

    这是因为您将一个方法传递给then 回调并且this 被重新定义。要让this 指向Parent 的实例,请在then 回调中使用箭头函数。

    还有其他方法可以做到这一点,请参阅上一个问题的优秀答案:How to access the correct `this` inside a callback?

    带有箭头功能的代码

    class Parent {
      constructor() {
        this.driver = []
      }
      test() {
        this.method1()
        .then(() => this.method2())
        .then(() => {
          console.log('all done', this.driver)
        })
        .catch(err => {
          console.log('Something went wrong', err);
        });
      }
      method1() {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            this.driver.push('0');
            resolve();
          },200)
        });
      }
      method2() {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            this.driver.push('1');
            resolve();
          },200)
        });
      }
    }
    
    let instance = new Parent();
    instance.test();

    【讨论】:

      【解决方案2】:

      当你在这里传递method2

      .then(this.method2)
      

      method2 失去与this 的绑定

      试试

      .then(x => this.method2(x))
      

      或者

      .then(this.method2.bind(this))
      

      【讨论】:

      • 好的,当我有像上面这样的链时,我如何通过解析传递一些变量?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 2017-02-05
      • 1970-01-01
      • 2015-04-15
      相关资源
      最近更新 更多