我有一个从数据库中提取的小部件列表,每个小部件都使用switch语句加载。我遇到的问题是,如果一个getJson
呼叫在另一个呼叫之前完成,即使其进一步下线,它也会无序加载。如何防止这种情况发生,以便按顺序加载?
var DashboardArray = DashBoardItems.split(",");
for (index = 0; index < DashboardArray.length; index++) {
switch (DashboardArray[index]) {
case 'totalHours':
$.getJSON(hoursByType, function (json) { hrsByTypeJSON = json; HoursByType(); });
break;
case 'invoiceList':
InvoiceListNav();
break;
case 'prevInvoiceWidget':
PreviousInvoice();
break;
case 'payrollSchWidget':
PayrollSchedule();
break;
case 'empListWidget':
EmployeeList();
break;
case 'executiveOverview':
$.getJSON(execOverview, function (json) { execOverJSON = json; ExecOverView(); });
break;
case 'grossWagesDept':
$.getJSON(dashboardURL, function (json) { gwdJSON = json; WagesByDept(); });
break;
case 'grosswagesbyTrend':
$.getJSON(wagesByTrend, function (json) { wageTrendJSON = json; grosswagesbyTrend();});
break;
case 'wagesPos':
$.getJSON(wagesByPosition, function (json) { posJSON = json; WagesByPos(); });
break;
case 'totalreghoursbyTrend':
$.getJSON(RegHrsTrend, function (json1) {
RegHrTrendJSON = json1;
$.getJSON(OTHrsTrend, function (json2) {
OTHrTrendJSON = json2;
$.getJSON(PTOHrsTrend, function (json3) {
PTOHrTrendJSON = json3;
$.getJSON(OtherHrsTrend, function (json4) {
OtherHrTrendJSON = json4;
totalRegHoursTrend();
});
});
});
});
break;
case 'employeeByType':
empTypePie();
break;
case 'totalInvoice':
$.getJSON(totalInvoice, function (json) { TTLInvJSON = json; TotalInvoice(); });
break;
case 'totalInvoiceDept':
$.getJSON(InvoiceByDiv, function (json) { InvDivJSON = json; TotalInvoiceDept(); });
break;
case 'totalinvoicebyTrend':
$.getJSON(InvoiceTrend, function (json) { InvTrendJSON = json; totalInvoiceTrend(); });
break;
}
答案 0 :(得分:2)
这需要一个很大的promises数组。然后,您可以在所有承诺都已解决后执行所有初始化代码。
您有大量请求,因此只会处理totalreghoursbyTrend
var promises = [];
for (index = 0; index < DashboardArray.length; index++) {
switch (DashboardArray[index]) {
....
case 'totalreghoursbyTrend':
var request = $.getJSON(RegHrsTrend, function(json1) {
RegHrTrendJSON = json1;
}).then(function() {
return $.getJSON(OTHrsTrend, function(json2) {
OTHrTrendJSON = json2;
});
}).then(function() {
return $.getJSON(PTOHrsTrend, function(json3) {
PTOHrTrendJSON = json3;
});
}).then(function() {
return $.getJSON(OtherHrsTrend, function(json4) {
OtherHrTrendJSON = json4;
//totalRegHoursTrend(); MOVE TO $.when().done()
});
});
promises.push(request)
break;
}
}
// fires when all promises pushed to array are resolved
$.when.apply(null, promises).done() {
// initialize all widgets here in preferred order
totalRegHoursTrend();
}).fail(function(f1Val, f2Val) {
alert('Ooops....something in the promise chain got rejected');
});
我没有看到这些嵌套调用之间存在任何关系,所以实际上它们可以在另一个$.when()
中同时调用,并将该promise推送到promise数组