1

当使用 jQuery Deferred 类加载模块时,我得到了一些奇怪的行为。完成加载队列写入“所有模块已加载”的回调在队列完成之前触发。我对延迟模式的使用是错误的吗?

var ModuleMgr = {
    [...]
loadModule: function(name){
        var deferred = new $.Deferred();
        var module = ModuleMgr.getModuleByName(name);
        module.init(function(result){
            deferred.resolve(1);
        });
        return deferred;
    },

    loadAll: function(onReady, onError){
            var self = ModuleMgr;
        var promises = [];
        for ( var current in self.needLoading ){
            var module_name = self.needLoading.pop();
            try{
                var d = self.loadModule(module_name);
                promises.push(d.promise());
            }
            catch(e){
                console.log('Failed to load module' +module_name);
                self.needLoading.push(module_name);
                setTimeout(self.loadAll, 2000); // Try again
            }
        }

        $.when.apply(null, promises).then(
            function(status){
            console.log('All Modules loaded');
        }, function(status){
            console.log('Error happended: '+ status);
        }, function(status){
            console.log('Status'+ status);
        });
    }
}
4

0 回答 0