for 循环元素的执行时间比内部 AJAX 调用可以响应的要快

Execution time of for loop over elements is faster than the inner AJAX call can respond

本文关键字:响应 调用 内部 元素 循环 执行时间 for AJAX      更新时间:2023-09-26

我有函数LoadTempMovieList(),需要从sessionStorage加载电影。但是似乎 for 循环的执行时间比我所做的 AJAX 调用可以响应的要快,因此最终输出的顺序有时不正确。如何解决这个问题?

function LoadTempMovieList(){
  var obList = [];
  if(sessionStorage.struct != null){
    alert(sessionStorage.struct);
    obList = sessionStorage.struct.split(",");
    for(var i=0; i<obList.length;i++){
      MovieLoader(obList[i],"movie");
      //it use setTimeOut(), the problem also present 
    }
  }
}

更新

function MovieLoader(name,type,movieArray){
  $.ajax({
    ...
    data:{shortName:name,type:type},
    dataType:'html',
    success:function (html){
      if(html!="0"){
        ...
      }else{
        ...
      }
    }
  });
}

我引入了递归来按照对象在数组中的顺序加载对象。我还介绍了一些您可能觉得不需要包含的代码来验证我们有一个数组(以防一些错误的其他函数调用这个,或者其他什么)

function LoadTempMovieList(){
  var obList = [];
  if(sessionStorage.struct != null){
    alert(sessionStorage.struct);
    obList = sessionStorage.struct.split(",");
    LoadMoviesInOrder(obList);
  }
}
function LoadMoviesInOrder(movies){
  if( Object.prototype.toString.call( movies ) === '[object Array]' ){
    //get the very first object in the array, take it off the array
    var movie = movies.shift();
    MovieLoader(movie,"movie",movies);
  }
}
function MovieLoader(name,type,movieArray){
  $.ajax({
    ...
    data:{shortName:name,type:type},
    dataType:'html',
    success:function (html){
      if(html!="0"){
        ...
        if (movieArray.length) { //test to see if there are more movies left by using truthiness
          //wait 50 ms and call this function again, so that we achieve recursion
          setTimeout(function(){LoadMoviesInOrder(movieArray); }, 50);
        }
      }else{
        ...
      }
    }
  });
}

如果你在原始问题中引用的ajax调用(在其他人编辑之前)是异步的,那么你将不得不使用ajax调用的完成函数来触发对MovieLoader的下一次调用。

由于 ajax 调用需要不确定的时间才能完成,因此尝试使用某种 setTimeout() 来猜测 ajax 调用需要多长时间并不完全可靠。 对 ajax 结果进行排序的唯一 100% 可靠方法是对 ajax 调用进行排序,并且在第一个调用完成之前不启动下一个 ajax 调用,等等......

您没有向我们展示您的实际 ajax 调用,因此我们无法更具体地说明实现此调用的最佳方式。