JQuery的阻断的非同步初始化 [英] JQuery blocking for an asynch initialization

查看:152
本文介绍了JQuery的阻断的非同步初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个SignalR枢纽AngularJS服务。这里是我厂的服务:

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;
    }])

这code将是完美的,除了那个。开始()调用是异步的,和的枢纽还没有返回经理的时候开始完成。基本上,我想阻止,直到开始返回是经理之前完成。在。开始()方法返回一个jQuery 递延对象,我猜是答案的一部分,但我不知道如何使用它没有一个回调函数?

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?

推荐答案

类似下面应该做的伎俩。

Something like the following should do the trick.

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

现在回调函数会返回一个延迟/承诺过,所以服务消费者将需要期待的。您消费code可能是这个样子:

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();
});

有关 jQuery的递延的文档是在这里。特别是要检查出 Deferred.then()

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

需要注意的是:

在deferred.then()方法返回一个新的承诺,可以过滤状态和的通过函数递延值......这些过滤器功能,可以返回一起承诺的.done传递一个新的值()或.fail()回调,或者他们可以返回另一个观察的对象(推迟,承诺等)将通过它解决/拒绝的状态和价值观的承诺的回调...

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

更新

这是另一种方法(也可能是更好的办法 - 因为它不会要求您处理消费者的承诺)是为了让轮毂完全初始化,设置你的工厂,并拉开了您的应用程序控制器之前。事情是这样的......

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

});

这篇关于JQuery的阻断的非同步初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆