Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Waiting/blocking until constructor is completely loaded

The JavaScript API that I am creating has the following structure:

var engine = new Engine({
    engineName: "TestEngine",
    engineHost: "localhost"
});

// I don't want to proceed to the next line until Engine is fully loaded
// But the following part of the API is immediately called before the above is loaded
engine.startCar(
    "car_name",
    "car_id"
);

The "Engine" instance takes a few seconds to load (1-2 seconds). So until then, engine.startCar should NOT be called.

How do I make internal changes to the constructor ( new Engine() ) such that, it doesn't return the instance until it is fully loaded?

like image 494
BlueChips23 Avatar asked Sep 23 '26 22:09

BlueChips23


1 Answers

This is a standard problem in JavaScript. Normally it occurs when you make AJAX requests, but timeout-based deferreds have the same basic issue.

jQuery, and most libraries with this sort of issue, solve this problem by having an initial method which returns a "deferred" or "promise" object that can be used to say "when X is done, do Y".

This is best explained by example. If you do the following in your Engine constructor:

function Engine(option) {
     var readyDeferred = new $.Deferred();
     this.ready = readyDeferred;
     window.setTimeout(1000, function() {
         readyDeferred.resolve();
     }
}

You when you build an engine you can simply do the following:

var engine = new Engine({...});
engine.ready.done(function() {
    // start your engines!
});

Of course, since times vary on client machines, it'd be even better if you could use some logic other than a window.setTimeout to trigger your readyDeferred.resolve();. For instance, you might trigger it when all of your AJAX requests have finished, which would be more predictable than any specific wait time.

like image 83
machineghost Avatar answered Sep 26 '26 07:09

machineghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!