2

Example:

var readBackend = function(){
    var deferred = q.defer();
    readData().then(function(data) {
         deferred.resolve(data);
      })
    return deferred.promise;
}

class Test {
    constructor(){
        readBackend().then(function(data) {
            this.importantData = data;
        })
    }

    someFunc() {
        //iterate over important data, but important data is defined
        //promise didnt resolved yet
    }

}

var test = new Test();
test.someFunc(); //throws exception!

Is there any way to ensure, that object properties are initiated by constructor, when I call someFunc?

The only way which comes to my mind is creating init function, which will return promise, but then, everytime I use my class, I would rely on init function to work properly

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Raston
  • 91
  • 2
  • 10
  • [Don't do asynchronous data loading in your constructor](http://stackoverflow.com/q/24398699/1048572). – Bergi May 20 '16 at 17:53

1 Answers1

6

Is there any way to ensure, that object properties are initiated by constructor, when I call someFunc?

Not without restructuring your code. You cannot have your constructor perform asynchronous operations and expect your synchronous methods to work.


I see two possible solutions:

1. Have a static method which loads the data and returns a new instance of your class:

class Test {
    static createFromBackend() {
      return readBackend().then(data => new Test(data));
    }

    constructor(data){
      this.importantData = data;
    }

    someFunc() {
      // iterate over important data
    }
}

Test.createFromBackend().then(test => {
  test.someFunc();
});

This ensures that the data is available when the instance is created and you can keep the API of the class synchronous.

2. Store the promise on the object:

class Test {
    constructor(){
      this.importantData = readBackend();
    }

    someFunc() {
      this.importantData.then(data => {
        // iterate over important data
      });
    }
}

Of course if someFunc is supposed to return something, that would require it to return a promise as well. I.e. the API of your class is asynchronous now.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143