I have a bunch of files to iterate over. For each file, depending on some of the field values, I may or may not need to make asynchronous AJAX requests to get additional data. After all these requests have resolved I want to append the relevant data for that file to the web page before continuing to the next file. My actual code contains irrelevant info, but the logic resembles the following pseudocode:
var chain = $.when();
for(x = 0; x < files.length; x++) {
console.log('FOO');
chain = chain.then(function() {
var fieldNamePromises = [];
var fieldName2Promises = [];
if ('fieldName' in files[x]) {
//getFieldNameData returns an AJAX request
fieldNamePromises.push(getFieldNameData())
}
if ('fieldName2' in files[x]) {
//getField2NameData returns an AJAX request
fieldName2Promises.push(getFieldName2Data())
}
Promise.all(fieldNamePromises.concat(fieldName2Promises)).then(function() {
console.log('BAR');
})
});
}
For me, this would log:
'FOO'
'FOO'
'FOO'
'BAR'
'BAR'
'BAR'
Whereas I want:
'FOO'
'BAR'
'FOO'
'BAR'
'FOO'
'BAR'
How can I force it to wait for all my asynchronous requests to finish before continuing in my loop?
The following also produces three FOOs followed by three BARs instead of FOO BAR alternating.
getFileHistory(fileNumber, function (files) {
var chain = $.when();
for (let x = 0; x < files.length; x++) {
chain = chain.then(function () {
console.log('FOO');
var fieldNamePromises = [];
fieldNamePromises.push(getData('Data', function () { }))
fieldNamePromises.push(getData('Data', function () { }))
return Promise.all(fieldNamePromises).then(function () {
console.log('BAR');
})
});
}
});
function getFileHistory(fileNumber, callback) {
var url = window.baseUrl + "api/get-file-history/filter?fileNumber=" + fileNumber;
return $.ajax({
type: 'GET',
url: url,
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (result) {
callback(result);
}
});
}
function getData(id, callback) {
var url = "api/" + id;
return $.ajax({
type: 'GET',
url: url,
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (result) {
callback(result);
},
error: function (error) {
console.log(error);
}
});
}
Update: when I remove the loop from getFileHistory (another AJAX call), it returns the FOO/BARs as expected. Not entirely sure why this makes a difference.