在课堂上链接承诺[重复]

问题描述 投票:0回答:2

我上课时我正试图将这样的承诺链接起来:

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导致错误

未捕获的TypeError:无法读取未定义的属性“driver”

javascript class promise
2个回答
0
投票

当你在这里通过method2

.then(this.method2)

qazxsw poi失去了对qazxsw poi的约束力

尝试

method2

要么

this

0
投票

它正在发生,因为您将方法传递给.then(x => this.method2(x)) 回调并且.then(this.method2.bind(this)) 被重新定义。为了让then指向this的实例,请在this回调中使用箭头函数。

还有其他方法可以做到这一点,请参阅上一个问题的优秀答案:Parent

Your Code with Arrow Function

then
© www.soinside.com 2019 - 2024. All rights reserved.