Skip to content Skip to sidebar Skip to footer

Jquery Blocking For An Asynch Initialization

I'm writing an AngularJS service for a SignalR hub. Here's my factory for the service: .factory('gameManager', [function () { $.connection.hub.start(); var manager

Solution 1:

Something like the following should do the trick.

app.factory('gameManager', [function () { 
    return $.connection.hub.start().then(function() {
      return $.connection.gameManager;
    });
}])

Now your callback function will return a deferred/promise too, so the service consumer will need to be expecting that. Your consuming code might look something like this:

gameManager.then(function(gameManager) {

  // do whatever with game manager
  gameManager.doSomething();
});

The docs for jquery Deferred are here. In particular, check out Deferred.then().

Note that:

the deferred.then() method returns a new promise that can filter the status and values of a deferred through a function ... These filter functions can return a new value to be passed along to the promise's .done() or .fail() callbacks, or they can return another observable object (Deferred, Promise, etc) which will pass its resolved / rejected status and values to the promise's callbacks...


update:

An alternate approach (and probably the better approach - since it won't require that your consumer handle the promise) is to let the hub initialize completely, before setting up your factory, and kicking off your app controller. Something like this...

$.connection.hub.start().then(function() {
  app.factory('gameManager', function() {
    return $.connection.gameManager;
  });

  // ...// kick off the rest of the app..

});

Solution 2:

You will not find what you are looking for, you will have to go with Lee's answer. Javascript is mostly single-threaded and does not allow blocking (with specific exceptions, such as alert window or synchronous ajax call).

Post a Comment for "Jquery Blocking For An Asynch Initialization"