课堂上的承诺

时间:2019-03-07 21:06:03

标签: javascript class promise

我上了一堂课,试图像这样链接诺言:

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'

2 个答案:

答案 0 :(得分:0)

当您在此处通过method2

.then(this.method2)

method2失去了对this的约束力

尝试

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

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

答案 1 :(得分:0)

之所以发生,是因为您正在向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();