2016-09-19 24 views
3

现在我已经得到了一些代码,发生在我想装载等待所有功能和要求完成

的script.js

moduleLoader.load([ 
    'mainModule', 
    'aboutUsModule', 
    'featuresModule', 
    'messageModule' 
]); 

该模块的字符串数组moduleLoader.load函数在数组上执行$.each循环,然后继续获取有关每个模块的必需信息。

ModuleLoader组件

var load = function (modules) { 
    $.each(modules, function (index, module) { 
     getConfig(module); 
    }); 
}; 

getConfig

var getConfig = function (module) { 
    $.get(module + '/config.json').done(function (config) { 
     console.log(config); 
     getData(config); 
    }).fail(function() { 
     console.error('Couldn\'t find a config file for module: ' + module); 
     return 0; 
    }); 
}; 

然后你就可以在getConfig回调,它继续得到数据,这也是异步看到的,然后它有两个以上那是异步的步骤。

所以基本上里面的回调回调里面回调...等等。

只是,我把它分成功能,使它看起来更好一点。

现在我可以获得所有的信息,但每次都会加载不同的信息,所以有可能知道所有ajax请求何时完成,然后执行某些操作?

回答

2

您可以使用jQuery的功能$.when()这不正是你所需要的: https://api.jquery.com/jquery.when/

为了让你的代码工作,你可以重构一个位:

var XHRs = []; 

var load = function (modules) { 
    $.each(modules, function (index, module) { 
    XHRs.push(getConfig(module)); 
    }); 
}; 

$.when(XHRs).then(function() { 
    // do something 
}); 

,也是你的getConfig()函数应该返回$.get。这是可行的,因为jQuery中的$ .ajax创建了一个Deferred对象,它实际上可以让你链接你的函数或让它们彼此等待。

以供将来参考: https://api.jquery.com/jquery.deferred/

+0

然后,你有一个全球'XHRs'变量? – Neal

2

您可以利用承诺链接,并将它们全部组合在一起,做一些事情时,他们都做(有点像这样):

var load = function (modules) { 
    var promises = modules.map(getConfig); 

    // can use $.when or Promise.all here 
    $.when.apply($, promises).then(function() { 
     // do something when all done 
    }); 
}; 

var getConfig = function (module) { 
    // $.get returns a jqXHR which is "thennable" 
    return $.get(module + '/config.json').then(function (config) { 
     console.log(config); 
     // if this also returns a promise then it will 
     // wait till this one is done as well in the promise chain 
     return getData(config); 
    }, function() { 
     console.error('Couldn\'t find a config file for module: ' + module); 
     return 0; 
    }); 
}; 
+0

如果至少有一个请求失败会怎么样?我想这会让更多的问题,但只是说... –

+0

@ A.Wolff可能是第二个fn进入'$ .when'然后 – Neal

+0

我刚才看到OP要求'当所有的ajax请求都完成了'所以实际上你的答案会按预期工作。我更想知道如何使用always()而不是'then(successHandler)',但是就像我刚刚说的那样,忘记我的第一条评论;) –

0

如果你有没有其他未决的Ajax请求,然后使用相关的全球ajax事件ajaxStop

$(document).one('ajaxStop', function() { 
    // all ajax requests has finished 
}); 
+0

但是当你停止使用jquery时,它全部坏了;-) – Neal

+0

@Neal We生活在一个愚蠢的世界肯定... –