当多个asyc调用完成时,AJAX启动最后一个asic调用

AJAX launch final asyc call when multiple asyc calls are complete

本文关键字:调用 AJAX 启动 最后一个 asic 完成时 asyc      更新时间:2023-09-26

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

我尝试使用多个标志来显示异步调用是否完成,并使用一个块函数来阻止进程,直到可以进行最后一次调用。

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的方式而不是暴力块函数来实现这一点?提前感谢!

您正在寻找承诺。

这篇文章很好地解释了基础知识。虽然许多浏览器现在都在原生地支持它们(除了IE),但您仍然希望包含一个类似于es-6的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);
    }
);

将检查移到d()中,并调用a、b和c 的done(..)(除非您希望它在上发生,无论它是否成功-在这种情况下使用always(..)

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;
          d();
      });
}
//same flag+function for b() and c()
function d(){
    if(aFinished&&bFinished&&cFinished){
        var jsonData=$.ajax(...).done(...);
    }
}
a();b();c();

那么就不需要blockTillAllDonesetTimeout

您可以尝试基于事件的方法。将方法a()b()c()放在一个类中,如果这三个方法都完成了,则每次检查都完成,如果完成,则引发一个将由侦听器捕获的事件,然后它可以执行d()

我将尝试使用代码演示这一点