如何在ajax完成后执行第二次循环迭代

how to execute second loop iteration after ajax done

本文关键字:执行 第二次 循环 迭代 ajax      更新时间:2023-09-26

如何延迟循环,直到函数"some_multi_ax_function()"更改全局变量(exe_counter将为0)?

for (i = 0; i < some_data_list.length; i++) {
    exe_counter=1;
     if(i>0 && exe_counter != 0){
            delay{
                // delay for loop until some_multi_ajax_function() set exe_counter = 0
                // do not execute second iteration
            }
      }else{
            data = some_data_list[i];
           // Many ajax posts will be executed here. In the end exe_counter will be set to 0;
           some_multi_ajax_function(data);
      }
}
function some_multi_ajax_function(data){
    $.ajax({
            ...
      }.done(function(d) {
           // here it could be used another ajax function 
           exe_counter = 0;
      });
}

您使用错误的解决方案来解决问题。

如果您想等待Ajax操作,则必须仅使用回调。

然后递归地你应该做:

function some_multi_ajax_function(data, i) {
    $.ajax({
        ...
    }.done(function(d) {
         if (i < data.length) {
             some_multi_ajax_function(data, i + 1);
         } else {
             // Do something in the end
         }
    });
}
some_multi_ajax_function(some_data_list, 0);