Javascript 在异步代码块中处理的多个ajax延迟调用数组,后跟同步最终代码块

Javascript 在异步代码块中处理的多个ajax延迟调用数组,后跟同步最终代码块,javascript,jquery,ajax,jquery-deferred,Javascript,Jquery,Ajax,Jquery Deferred,我对jquery和ajax相对来说是个新手,我正在尝试使用延迟和承诺的概念来解决这个问题。 我想做以下工作: 调用URL列表并处理从URL返回的结果。我想首先并行处理结果,然后合并处理后的结果以得到最终结果 Th伪代码如下所示: var deferredAjaxCalls = []; for (var i = 0; i < jobsListLength; i++) { deferredAjaxCalls.push( $.ajax({ url:

我对jquery和ajax相对来说是个新手,我正在尝试使用延迟和承诺的概念来解决这个问题。 我想做以下工作: 调用URL列表并处理从URL返回的结果。我想首先并行处理结果,然后合并处理后的结果以得到最终结果

Th伪代码如下所示:

var deferredAjaxCalls = [];
for (var i = 0; i < jobsListLength; i++) {
    deferredAjaxCalls.push(
        $.ajax({
            url:"/myurl",
            method:"POST",
            contentType:"application/json",
            dataType:"json",
            data:mydata,
            success:function(result){
              //Some code here that is performance intensive
            } 
        });
}
$.when.apply(this,deferredAjaxCalls).done(function(){
    for (var k=0; k< arguments.length;k++){
            //combine the results of the individual results of the
            // success part of all the ajax calls and execute some more 
            //code synchronously
    } 
}).fail( function (jqXHR, status, error) {
   //Log failed status
 });
var deferredAjaxCalls=[];
对于(变量i=0;i
最初,我将所有代码从$.when.apply()中的成功部分移到了$.when.apply()中。但是,这导致了非常慢的性能,因为现在有很多密集的计算是同步执行的。因此,我正在寻找一种方法来独立执行部分代码,并同步执行最后一段代码

我确实读过关于使用承诺的内容,但在最终在when.apply()块中进行同步之前,找不到将承诺与具有中间处理的ajax调用数组一起使用的示例

解决这个问题的好办法是什么


谢谢!

您可以尝试使用延迟:

  var req_responses = [];
  var deferreds = [];

  for(var i in jobs) {
     deferreds[i] = new $.Deferred();
  }

  for(var i in jobs) {
     (function(i) {
        $.ajax ({
           url: ".",
           type: "POST",
           dataType: "json",
           done: function(response) {
              //process the response
              req_responses[i] = response;
              deferreds[i].resolve();
           }
        });
     })(i);   
  }

  $.when.apply(deferreds).then(function(os) {
     //all the responses are in req_responses
     //finish processing
     alert("done");
  });

从数组
jobsList
开始,您可能需要这样的内容:

var deferredAjaxCalls = jobsList.map(function(job) {
    return $.ajax({
        url: "/myurl",
        method: "POST",
        contentType: "application/json",
        dataType: "json",
        data: mydata
    }).then(process);// where `process` is a function that accepts $.ajax's (data, textStatus, jqXHR) and returns a *single* value/object - the result of the processing. This will standardise the data delivered below by $.when() to its success handler.
});
$.when.apply(null, deferredAjaxCalls).then(function() {
    // Due to `.then(process)` above, `arguments` are guaranteed to comprise one arg per ajax call.
    // Otherwise you potentially have the problem reported here - http://stackoverflow.com/questions/12050160/
    for (var k=0; k<arguments.length; k++) {
        // Combine the results of the individual results of the success part of all the ajax calls and execute some more code synchronously.
    }
    // In this function deliver an error by returning `$.Deferred().reject(new Error('myReason'))`
    return combined_result;
}, function(jqXHR, status, error) {
    // This hander will receive multiple $.ajax() params, which are best normalised into a single Error object. 
    return new Error(status); // similar to .then(process) above, reduce $.ajax's error args to a single "reason".
}).then(null, function(err) {
    // All errors delivered by code above arrive here as a js Error.
    // But please note that, in jQuery <v3.0, any uncaught errors above will genuinely throw (to the console).
    console.log(err.message);
});
var deferredAjaxCalls=jobsList.map(函数(作业){
返回$.ajax({
url:“/myurl”,
方法:“张贴”,
contentType:“应用程序/json”,
数据类型:“json”,
数据:mydata
}).then(process);//其中'process'是一个函数,它接受$.ajax(数据、textStatus、jqXHR)并返回一个*单个*值/对象-处理的结果。这将标准化下面由$.when()传递给成功处理程序的数据。
});
$.when.apply(null,deferredAjaxCalls).then(function(){
//由于上面的`.then(process)`的原因,`arguments`保证每个ajax调用包含一个arg。
//否则,您可能会在此处报告问题-http://stackoverflow.com/questions/12050160/

对于(var k=0;kPlease no!使用已返回承诺的异步进程交付的结果解析延迟(或承诺)被称为,应该避免
有一个
成功:
选项,它还返回一个承诺,承诺本身可以返回和/或用作承诺链的前导元素。有趣。因此解决方案是只使用完成回调而不是成功?Dane,更可能是
。then()
,这将允许返回一个处理后的结果,以便沿着承诺链向下传递(在本例中为$.when(…).then()的处理程序)。