【发布时间】:2019-05-31 16:52:04
【问题描述】:
我必须调用 Agile Central API 以获取缺陷套件列表,然后遍历列表并进行嵌套调用以获取每个套件中的缺陷列表,嵌套调用取决于外部调用.然后我必须将数据行附加到表中,然后调用 doneCallback() 来表示数据收集结束。我遇到的问题是在请求完成之前调用了 doneCallback(),因此实际上并没有传递任何数据
我已经尝试了这篇文章中的方法:Wait until all jQuery Ajax requests are done? 和这篇文章:how to wait until Array is filled (asynchronous)。在控制台中,我可以看到我想要的所有数据都在那里,但没有附加任何数据。我的问题是:如何确保在循环中发出的所有请求都完成并推送数据之前不调用 doneCallback()?这是我现在的代码:
function getSuites() {
return $.ajax({
url: suitesURL("71101309592") + "&fetch=Name,FormattedID,Defects",
type: "GET",
xhrFields: {
withCredentials: true
},
headers: {
"zsessionid": apiKey
}
});
}
function getDefects(_ref) {
return $.ajax({
url: _ref,
type:"GET",
xhrFields: {
withCredentials: true
},
headers: {
"zsessionid": apiKey
}
});
}
// Download the data
myConnector.getData = function (table, doneCallback) {
console.log("Getting Data...");
var ajaxCalls = [], tableData = [];
var suitesJSON = getSuites();
suitesJSON.done(function(data) {
var suites = data.QueryResult.Results;
for(var i = 0; i < suites.length; i++) {
(function(i) {
var defectsJSON = getDefects(suites[i].Defects._ref + "?fetch=Name,FormattedID,State,Priority,CreationDate,c_RootCause,c_RootCauseCRM");
ajaxCalls.push(defectsJSON);
defectsJSON.done(function(data) {
var defects = data.QueryResult.Results;
for(var j = 0; j < defects.length; j++) {
tableData.push({
"suiteName": suites[i].Name, // This is the name of the suite collected in the outer call
"defectName": defects[j].Name,
"FormattedID": defects[j].FormattedID,
"State": defects[j].State,
"Priority": defects[j].Priority,
"CreationDate": defects[j].CreationDate,
"RootCause": defects[j].c_RootCause,
"RootCauseCRM": defects[j].c_RootCauseCRM
});
}
});
})(i);
}
});
$.when.apply($, ajaxCalls).then(function() {
console.log(tableData);
table.appendRows(tableData);
doneCallback();
});
};
【问题讨论】:
-
jQuery when() 与 ajax 调用应该没问题....
-
抱歉,我对使用 ajax 很陌生...请您再解释一下吗?
标签: javascript ajax asynchronous