javascript - Is there a design pattern to manage parallel AJAX queries? -


i developing web application retrieving data several web services (let's 2 simplify). has retrieved 1 service not depend on has been retrieved other, can launch ajax requests in parallel. need perform actions once both queries have returned data. since seems usual, wondering if there well-formalised , accepted design pattern that. doing far there (using jquery):

var data1 = null; var data2 = null;  $.ajax({     url : url1,     success: function(data) {         data1 = data;         if(data2) perform();     }, });  $.ajax({     url : url2,     success: function(data) {         data2 = data;         if(data1) perform();     }, });  function perform() {     //do interesting stuff on data1 , data2 } 

would as-well ?

you can

check : jquery: api.jquery.com/jquery.when

we can use jquery's $.when() method, takes list of these "deferred" objects (all jquery ajax methods return deferred objects) , provides single callback.

syntax

$.when(    // deferred object (probably ajax request),    // deferred object (probably ajax request),    // deferred object (probably ajax request)  ).then(function() {    // have been resolved (or rejected), thing  }); 

example :

$.when($.ajax("/page1.php"), $.ajax("/page2.php"))   .then(myfunc, myfailure); 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -