Using jQuery promises, I'm trying to:
- Call an API for all possible values (of an animal)
- Call an API method for each animal (animal sound)
- Notify when each animal sound comes back - let's say it takes a while to work out
- Notify when all animal sounds have been returned
I'm putting all the animal sound functions into an array then calling $.when()
. I expect this to resolve when all animal sounds have returned, but I'm finding that it resolves immediately. Does anyone know what I'm doing wrong?
function () {
$('#txtNotification').text('Started ....');
$.ajax({
url: "/api/animals/all"
}).done(function(data) {
var animalFunctions = [];
for (var animalType of data) {
var animalFunction = $.ajax({
url: "/api/animal/sound/" + animalType
}).done(function(data) {
$('#txtNotification').text(data);
});
animalFunctions.push(animalFunction);
}
$.when(animalFunctions).then(function() {
$('#txtNotification').text('Done.');
});
});
}