I am trying to load a bunch of data from an API Async and when all the data is loaded I want to trigger an event that all the data is loaded. The problem I am having is that the API I am using limits the number of response objects to five. And I would potentially need to retrieve 30-40 response objects.
So what I want to do is create a when - then statement that loops trough the data items and makes request for every five items then when all the items are loaded I want to fire a loaded event. The issue I am having is that the when-then statement is completing before the success of the ajax request.
onto the code I have tried.
function loadsLotsOfStats(stats, dataType, eventName, dataName, callback) {
var groupedStats = [];
while (stats.length > 0) {
groupedStats.push(stats.splice(0, 5).join('/'));
}
j$.when(
groupedStats.forEach(function (d) {
loadJSONToData(model.apiUrl.replace("{IDS}", d), "json", "", dataName, function (d) { /*console.log(d);*/ }, true)
})
).then(function () {
j$(eventSource).trigger('dataLoaded', eventName);
});
The loadJSONToData function is basically just a wrapper function for an Async $.ajax.
so yeah the event is getting triggered before the data is actually loaded. Also for some reason if I try to put for loop right in the when( statement it through a syntax error?
Does anyone have any advice on how I could make a bunch of Ajax requests and wait until they all are compeleted before triggering an event? Or a away to fix what I currently have?
Thanks in advance for the help.
if(condition.length < 10) { // code to execute }
. – Oraorabel