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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.