0

I have class in which I'm trying to chain promises like this:

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();

but method2 is causing error

Uncaught TypeError: Cannot read property 'driver' of undefined

Igor
  • 60,821
  • 10
  • 100
  • 175
BT101
  • 3,666
  • 10
  • 41
  • 90

2 Answers2

0

When you pass method2 here

.then(this.method2)

method2 losses its binding to this

Try

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

Or

.then(this.method2.bind(this))
spender
  • 117,338
  • 33
  • 229
  • 351
0

It is occuring because you are passing a method to the then callback and this gets redefined. To keep this pointing at the instance of Parent use an arrow function in the then callback.

There are other ways to do this, see the excellent answer from this previous question: How to access the correct `this` inside a callback?

Your Code with Arrow Function

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();
Igor
  • 60,821
  • 10
  • 100
  • 175