jquery - Wait for async ajax requests to finish -


i'd write function performs dozen async ajax requests, wait of finish , return aggregated info. like:

function counthealthy(urls) {   var healthy = 0;   (var = 0; < urls.length; ++i) {     $.ajax({url: urls[i], async: true, id: i})     .done(function (data) { ++healthy; });   }   // wait ajax finish.   return healthy; } 

ps: ++healthy thread safe?

javascript doesn't have threads thread safety not issue. return statement problem, needs go in callback ajax calls execute on completion. since ajax happens asynchronously, code stands, return statement fire before requests return.

you might want check out query deferreds, seems born type of thing. directly link

function doajax() {   return $.get('foo.htm'); }  function domoreajax() {   return $.get('bar.htm'); }  $.when( doajax(), domoreajax() )   .done(function() {     console.log( 'i fire once both ajax requests have completed!' );   })   .fail(function() {     console.log( 'i fire if 1 or more requests failed.' );   }); 

with minor refactoring implement in 2 minutes.

alternatively, if control server, create server endpoint checking in 1 request.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -