Reputation: 3293
I have a massive each loop, and each iteration makes an ajax request:
$('.test').each(function() {
$.ajax(function() {...})
.done(function { ... });
}
After executing every iteration, I want to execute another function that alerts. To do this, I tried using promise()
$('.test').each(function() {
...
}).promise().done(function () {alert("This is an alert");});
However, that doesn't work: the alert executes before the each loop is finished. Any suggestions?
Upvotes: 0
Views: 228
Reputation: 5939
You need to trigger the alert within the ajax so you know it finished loading the code. Do this...
var totalCount=$('#test').length;
var ajaxCounter=0;
$('#test').each(function() {
$.ajax(function() {
//do stuff here
})
.done(function {
//do other stuff here
ajaxCounter++;
if(ajaxCounter==totalCount){
alert('this is an alert at the end');
}
});
}
If there is a chance that some of the ajax calls won't fire you might also want to use a setTimer to set off the alert if too much time passes... or just use the deferred fail method to keep track of them like this:
var totalCount=$('#test').length;
var ajaxCounter=0;
$('#test').each(function() {
$.ajax(function() {
//do stuff here
})
.done(checkAjaxFinished)
.fail(checkAjaxFinished);
}
function checkAjaxFinished(){
ajaxCounter++;
if(ajaxCounter==totalCount){
alert('this is an alert at the end');
}
}
Upvotes: 2
Reputation: 590
Yea like Lenny said, your code is executing just fine.
$('#test').each(function() {
...
}).promise().done(function () {alert("This is an alert");});
will setup all your ajax calls to run but not wait for each call to complete. Thats why the alert is happening before the calls complete. your promise object is on the each loop not the ajax calls. If you add a promise().done()/complete()
to each of the ajax calls and count how many of them are complete you can know when all of them are done.
Upvotes: -1
Reputation: 15699
ID
s must be unique.
Use class instead.
Also, ajax
calls will not work in loop. Better way to handle is to use recursive function.
Try:
Assuming you have classes called test
.
var len = $('.test').length;
call_ajax(0);
function call_ajax(i){
$.ajax(function() {...})
.complete(function {
if(i < len){
call_ajax(i+1); //recursive call
}
});
}
Upvotes: 0