Skip to content Skip to sidebar Skip to footer

Asynchronous Data Loading In Class Constructor

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

Solution 1:

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:

classTest {
    staticcreateFromBackend() {
      returnreadBackend().then(data =>newTest(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:

classTest {
    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.

Post a Comment for "Asynchronous Data Loading In Class Constructor"