【问题标题】:Convert async calls to sync?将异步调用转换为同步?
【发布时间】:2012-09-16 14:15:40
【问题描述】:

我在处理异步调用时遇到了问题。

例如,我想用 requirejs 动态加载一些模块。 目前我使用订阅者-发布者模式。不幸的是,这使我的代码 在某些情况下确实令人困惑...:

想象在对象中有一个有效的事件系统

var loader = {
    load: function(modules) {
        // do a async requirejs call
        require(modules, function(){
            // map arguments to normal array
            var modules = [].slice().call(arguments);
            // fire loaded event, pass modules
            this.trigger('loaded', modules);
        }.bind(this));
    }
};


var parent = {
    // do some initialization work
    initialize: function() {
        // execute the second initialization when our modules have finished loading async
        loader.on('loaded', this.secondInitialize, this);
        // require the given modules in the array
        loader.load(['one', 'two', 'three']);
    },

    secondInitialize: function(modules) {
        var three = new modules[2]();
        // do something with the 'three' module
    }

};

如您所见,这确实令人困惑。

还有其他设计模式可以很好地处理异步调用吗?

【问题讨论】:

  • 这是 Javascript 中异步工作方式的不幸副作用。没有包罗万象的解决方案。
  • @usr 可能不是万能的,而是另一种选择?

标签: javascript design-patterns asynchronous publish-subscribe


【解决方案1】:

查看jQuery Deferred object。 (即使没有 jq,大多数库都有 javascript 承诺的实现)

有了它,你可以做这样的事情:

var loadingOne = getLibOne(); //returns a jquery deferred promise
var loadingTwo = getLibTwo(); //returns another one

var loadingAllLibraries = $.when(loadingOne, loadingTwo);
loadingAllLibraries.done(function(lib1, lib2) {
  //... stuff
});

不完全是你的场景,但你明白了。编写异步原子变得相对容易。

【讨论】:

  • @kyogron - 最好的方法是查看上面的链接并开始使用它。它看起来很吓人,但实际上并不是很复杂。您可以通过谷歌搜索“javascript promises”来查找更通用的想法
  • 听起来不错,看看我如何在我的项目中最好地实现这一点:)
  • @kyogron - 顺便说一下,后来的 jQuery 中引入的一个类似功能是回调 api.jquery.com/jQuery.Callbacks,它允许您快速创建发布/订阅队列
  • 现在它被规范化为 Javascript 中的 Promise :developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
猜你喜欢
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多