JQuery blocking for an asynch initialization

江枫思渺然 提交于 2019-12-11 18:06:02

问题


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 = $.connection.gameManager;
        return manager;
    }])

That code would be perfect, except that that .start() call is asynchronous, and the hub has not completed starting by the time the manager is returned. Basically, I want to block until the start is complete before returning the manager. The .start() method returns a Jquery deferred object, which I'm guessing is part of the answer, but I don't know how to use it without a callback function?


回答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..

});



回答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).



来源:https://stackoverflow.com/questions/14792335/jquery-blocking-for-an-asynch-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!