The constructor takes some time, and when the method is called, this.folders
is not yet defined. How do I allow getIt()
to wait until the constructor is complete?
function test() {
var t=this;
$.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
t.folders=returned;
});
}
test.prototype.getIt = function() {
return this.folders;
};
var myObj = new test();
console.log(myObj.getIt());
Since
$.getJSON()
is asynchronous, there is no way of prevetingtest()
from returning aftert.folders
is populated.You can use a callback:
Or a promise (in this example, using Q library):
The call is async so you should present a loading spinner and then remove it by populating the data you received.
If you want to run code after something initializes at some point without including a callback i.e. in your ajax request, one cross browser solution is to constantly check as in the following code,