当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

I am developing a web application retrieving data from several web services (let's say only two to simplify). What has to be retrieved from one service does not depend on what has been retrieved from the other, so I can launch AJAX requests in parallel. I need then to perform some actions once both queries have returned their data. Since it seems to be something very usual, I am wondering if there is a well-formalised and accepted design pattern to do that. What I am doing so far is 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 and data2

}

Would you do like that as-well ?

网友答案:

you can do like this

Check : jQuery: api.jquery.com/jquery.when

we can use jQuery's $.when() method, which takes a list of these "Deferred" objects (All jQuery Ajax methods return Deferred objects) and then provides a single callback.

Syntax

$.when(

  // Deferred object (probably Ajax request),

  // Deferred object (probably Ajax request),

  // Deferred object (probably Ajax request)

).then(function() {

  // All have been resolved (or rejected), do your thing

});

Example :

$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
  .then(myFunc, myFailure);
网友答案:

When I have multiple ajax queries I usually like to keep a list of URLs. I create a list of promises and apply the $.when function to them. Something like this:

var urls = [url1, url2];

var endpoints = [];
for (var i = 0; i < a.length; i+=1) {
  endpoints.push($.ajax(urls[i]));
}
$.when.apply($, endpoints).done(function () {
  // Function arguments array differs if we have one or more than one endpoint.
  // When called with one endpoint arguments is an array of three elements [data, textStatus, jqXHR].
  // When called with more than one endpoint arguments is an array of arrays [[data, textStatus, jqXHR], ...].
  // Normalize the single endpoint to the generic list one.
  var args = endpoints.length > 1 ? arguments : [arguments];
});

Or more concise:

var urls = ['page1', 'page2'];
$.when.apply($, $.map(urls, $.ajax)).done(function () {
  console.log(arguments);
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: