Reading a JSON-Service like this:
$.ajax({
url:'activeIDs',
success : function(data){ // data = [14,15]
var tableRows = [];
for (var dataIndex=0; dataIndex < data.length; dataIndex++) {
var isLast = dataIndex == (data.length - 1);
$.ajax({
url: 'info?id=' + data[dataIndex],
success: function(data2) { // "foo", "bar"
tableRows.push(data2.name);
if (isLast) {
alert(tableRows.length);
}
}
});
}
}
});
First network-trace is:
[14,15]
"foo"
"bar"
In this case the alert gives "2".
Seconds network-trace is different:
[14,15]
;"foo"
(now takes very long)"bar"
In this case the alert gives 1
after one second, this is bad!!!
How to use $.Deferred instead of isLast
?
Deferred() A factory function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
Definition and Usage. The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.
Asynchronous JavaScript is an alternative to Ajax in some cases and is a way to lighten the pages. It does not allow full interactivity with the server as does the XMLHttpRequest object.
Deferred method can be passed an optional function, which is called just before the method returns and is passed the new deferred object as both the this object and as the first argument to the function. The called function can attach callbacks using deferred. then() , for example.
You'll need to wait for all requests to finish before alert
ing.
$.ajax({
url:'activeIDs',
success : function(data){ // data = [14,15]
var tableRows = [];
var requests = [];
for (var dataIndex=0; dataIndex < data.length; dataIndex++) {
var isLast = dataIndex == data.length;
var request = $.ajax({
url: 'info?id=' + data[dataIndex]
}).done(function(data2) { // "foo", "bar"
tableRows.push(data2.name);
});
requests.push(request);
}
// wait for all requests to finish here
$.when(requests).then(function(){
// all success functions have been called and updated things appropriately
alert(tableRows.length);
}
}
});
This assumes that all requests succeed. It also looks like there are a few typos
tableRows
get updated?entries
defined?Edit
Now using promise style success handler. Should push the result in to tableRows
before calling the $.when().then
callback
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With