Reputation: 3166
I have the following data
var data = [{user:"somename"}, {user:"anothername"}];
I have this function that processes that that, let say checking user if it exist
function process(user) {
$.ajax({
url: 'http://domain.com/api',
success: function(result) {
if(result == 'success')
anotherFunction();
else
console.log('error');
}
})
}
function anotherFunction() {
$.ajax({
// do stuffs
})
}
$.each(data, function(k,v){ process(v.user); })
The $.each
will try to loop even the process
and the anotherFunction
hasn't finished yet
Question, what can I do to assure that all functions are finished executing before moving on to another index?
I heard I can use jquery deferred.
Upvotes: 0
Views: 768
Reputation: 339816
Collect the promises returned by your AJAX function, if necessary post-processing that result with .then
so that it calls anotherFunction()
which must also return
the result of $.ajax
.
function process() {
return $.ajax(...).then(function(result) {
if (result === 'success') {
return anotherFunction();
} else {
return null; // this might need to change...
}
});
}
function anotherFunction() {
return $.ajax(...);
}
var promises = [];
$.each(data, function(k, v) {
promises.push(process(v.data));
}
and then wait for all the promises to be resolved:
$.when.apply($, promises).done(function() {
// all done here
});
NB: in general it's good practise for an AJAX call to produce a non 2xx
return code for errors, rather than an error code within a "successful" HTTP call. This then allows the client side code to use normal AJAX error processing (i.e. .fail
callbacks) instead of checking for "errors" within AJAX success processing.
Upvotes: 1