0

I am writing some Node code with ES6. In my code, I have a class, that looks like the following. Please note, this is a basic example intended to isolate and show the problem.

class MyClass {
  constructor() {
    this.id = uuid();
    this.number = Math.floor((Math.random() * 100) + 1);
  }

  process() {
    this.validateNumber()
      .then(this.generateImage)
      .catch(function(err) {
        console.log(err);
      })
    ;
  }

  validateNumber() {
    let self = this;
    var promise = new Promise(function(resolve, reject) {
      // do stuff with self.number
      resolve({});
    });
  }

  generateImage() {
    console.log(this);
    // the above prints "undefined" in the console window
    // how do I get this.number again?

  }
}

In this class, you'll notice that I generate a random number in my constructor. I want that number to be usable throughout the methods in my class. However, since I have one method that chains together promises, it's like this loses meaning after validateNumber is executed.

how do I resolve this?

user70192
  • 13,786
  • 51
  • 160
  • 240

1 Answers1

-1

ES6 introduced a feature called arrow functions. Apart from the syntax being more concise than the conventional function syntax, it retains the context of this. Essentially, your code can be changed to the following:

var promise = new Promise((resolve, reject) => {
      console.log(this); // MyClass
      resolve({});
});

And you also need to retain the context inside the then

this.validateNumber()
    .then(() => this.generateImage());
Thomas Maddocks
  • 1,355
  • 9
  • 24