完成多个异步调用后,AJAX会启动最终的异步调用

奥兰多

我正在考虑如何更好地管理运行多个异步调用的顺序,以实现最佳的周转时间。基本上,过程是这样的:当网页开始加载时,它将显示该页面并启动几个AJAX调用a(),b()和c()。这三个步骤全部完成后,运行异步调用d()。当满足两个条件时,我检查了多个线程,例如jquery execute function,但这并不完全相同。

我尝试使用多个标志来显示异步调用是否已完成,并使用一个阻止函数来阻止该过程,直到可以拍摄最后一个调用为止。

var aFinished=false;
function a() {
      var jsonData = $.ajax({
        url: "${createLink(controller:'environment', action:'a')}",
        dataType: "json",
        async: true
      }).done(function(jsonData) {
          //do something
          aFinished=true;
    });
}
//same flag+function for b() and c()
function d(){
    blockTillAllDone();
    var jsonData=$.ajax(...).done(...);
}
function blockTillAllDone(){
    if(aFinished&&bFinished&&cFinished){
        console.log("Ok to continue");
        return;
    }
    else{
        console.log("Have to wait");
        setTimeout(blockTillAllDone(),2000);
    }
}
a();b();c();d();

由于递归块功能导致堆栈不断增长,因此性能并不是很好。是否有人有更好的主意,如何以更多的AJAX方式而不是暴力阻止功能来实现这一目标?提前致谢!

安迪·诺尔克(Andy Noelker)

您正在寻找承诺

本文在解释基本知识方面做得很好。尽管许多浏览器现在都在本地支持它们(IE除外),但您仍然需要包括诸如es-6 promise的polyfill 一旦开始使用诺言,您可以通过以下方式解决问题:

var a = new Promise(function(resolve,reject){
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: 'example.com/test/1',
        success: function(response){resolve(response);},
        error: function(response){reject(response);}
    });
});

var b = new Promise(function(resolve,reject){
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: 'example.com/test/1',
        success: function(response){resolve(response);},
        error: function(response){reject(response);}
    });
});

var c = new Promise(function(resolve,reject){
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: 'example.com/test/1',
        success: function(response){resolve(response);},
        error: function(response){reject(response);}
    });
});

//This will run once all async operations have successfully finished
Promise.all([a,b,c]).then(
    function(data){
        //everything successful, handle data here
        displayData(data);
    },
    function(data){
        //something failed, handle error here
        logoutError(data);
    }
);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章