Reputation: 6295
I have the following function that stores some data in ABC.PrintReport.reportData
.
I grab the data with AJAX requests. I then want to print the data in the new window that I open at the end of the getKeyData
function.
However, by the time the window opens, the AJAX requests have not returned the data, so I get errors about undefined properties. What is the solution to this?
getKeyData: function () {
for (var key in ABC.PrintReport.keyList) {
k = ABC.PrintReport.keyList[key].Report_Key;
ABC.PrintReport.reportData[k] = null;
(function(index) {
Ext.Ajax.request({
url: ABC.Core.servicePath + '/task/' + ABC.PrintReport.processInstanceID + '/report/' + ABC.PrintReport.keyList[key].Report_Key + '?portalID=' + ABC.Core.portalID,
success: function (response) {
ABC.PrintReport.reportData[index] = Ext.JSON.decode(response.responseText)[0];
}
});
})(k);
}
window.open(location.pathname + 'resources/printreport.html');
},
Upvotes: 2
Views: 137
Reputation: 3435
What about using deffered objects and promises? Though I don't see a method all()
that should help you resolve your problem, as shown here.
I suggest using a Q library, see the Combination section.
The all function returns a promise for an array of values. When this promise is fulfilled, the array contains the fulfillment values of the original promises, in the same order as those promises.
Then you do:
Q.allSettled(promises)
.then(function (results) {
window.open(location.pathName + 'recources/printreport.html');
});
It's more clean than using a counter of already succeeded requests.
Upvotes: 1
Reputation: 2122
Or you can use async lib, to create a parallel ajax calls and then call your callback with window.open
when all AJAX request are done.
Upvotes: 0
Reputation: 5832
Even though there are a variable number of requests going on, you can keep track of them and open the window in the success method when the last request completes.
getKeyData: function () {
var total = ABC.PrintReport.keyList.length;
var loaded = 0;
for (var key in ABC.PrintReport.keyList) {
k = ABC.PrintReport.keyList[key].Report_Key;
ABC.PrintReport.reportData[k] = null;
(function(index) {
Ext.Ajax.request({
url: ABC.Core.servicePath + '/task/' + ABC.PrintReport.processInstanceID + '/report/' + ABC.PrintReport.keyList[key].Report_Key + '?portalID=' + ABC.Core.portalID,
success: function (response) {
ABC.PrintReport.reportData[index] = Ext.JSON.decode(response.responseText)[0];
loaded++;
if (loaded == total) {
window.open(location.pathname + 'resources/printreport.html');
}
}
});
})(k);
}
},
Upvotes: 0