Javascript 是否有管理并行AJAX查询的设计模式?

Javascript 是否有管理并行AJAX查询的设计模式?,javascript,ajax,http,Javascript,Ajax,Http,我正在开发一个web应用程序,从多个web服务中检索数据(假设只有两个服务可以简化)。必须从一个服务中检索的内容并不取决于从另一个服务中检索的内容,因此我可以并行启动AJAX请求。一旦两个查询都返回了数据,我就需要执行一些操作。由于这似乎是非常常见的事情,我想知道是否有一个正式的和公认的设计模式来做到这一点。到目前为止,我正在做的是(使用jquery): 你也喜欢吗?你可以这样做 检查:jQuery:api.jQuery.com/jQuery.when 我们可以使用jQuery的$.when()

我正在开发一个web应用程序,从多个web服务中检索数据(假设只有两个服务可以简化)。必须从一个服务中检索的内容并不取决于从另一个服务中检索的内容,因此我可以并行启动AJAX请求。一旦两个查询都返回了数据,我就需要执行一些操作。由于这似乎是非常常见的事情,我想知道是否有一个正式的和公认的设计模式来做到这一点。到目前为止,我正在做的是(使用jquery):

你也喜欢吗?

你可以这样做

检查:jQuery:api.jQuery.com/jQuery.when

我们可以使用jQuery的
$.when()
方法,它获取这些“延迟”对象的列表(所有jQuery Ajax方法都返回延迟对象),然后提供一个回调

语法

$.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

});
例如:

$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
  .then(myFunc, myFailure);

当我有多个ajax查询时,我通常喜欢保留一个URL列表。我创建了一个承诺列表,并对其应用
$。when
函数。大概是这样的:

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];
});

这是基于Q库的吗?@Crozin是的,它似乎是基于Q库的。谢谢你的回答-这正是我想要的技巧。谢谢你的回答!我将把它用于查询的长列表。Async.js为处理异步方法组提供了一个很好的库。特别是,可以使用async.each()方法并行运行一组。async.js非常适合我的需要。但是因为我已经在使用JQuery,所以$.when().then();我想这更适合我的情况。无论如何,谢谢你。
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];
});
var urls = ['page1', 'page2'];
$.when.apply($, $.map(urls, $.ajax)).done(function () {
  console.log(arguments);
});