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

时间:2012-06-16 04:08:41

标签: javascript

我有函数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{
        ...
      }
    }
  });
}

2 个答案:

答案 0 :(得分:2)

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

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{
        ...
      }
    }
  });
}

答案 1 :(得分:2)

如果您在原始问题中提到的ajax调用(在其他人编辑之前)是异步的,那么您将必须使用ajax调用的完成功能来触发对MovieLoader的下一次调用。

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

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