javascript 异步多个 xmlhttp 请求

multiple xmlhttp requests with javascript asynchronously

我有一组电影片名,我正在通过 xmlhttp 请求检索它们的元数据。我只想使用 javascript 来尽可能保持它的亮度,就像它在移动设备上 运行 一样。当我异步执行此操作时,我得到 10 个相同的对象,这是我在数组中的最后一次搜索 url。如果我将 async 设置为 false,它工作正常,但显然这是不可取的。这是我的代码中与此问题相关的部分...

var movieObjArr = [];
var searchUrls = [
    // 10 search urls

];

function fetchMovieData(searchUrl) {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          var result = JSON.parse(xmlhttp.responseText);
          response(result);
      }
    }

    xmlhttp.open("GET", searchUrl, true);
    xmlhttp.send();
}

function response(result){
    movieObj.push(result);

    // once the movieObjArr has ALL the search results, display them
    // I must wait until all results are in because I then sort the array 
       so it's in alphabetical order
    if (movieObjArr.length == searchUrls.length){
        // call sort function
        // go through movieObjArr and display each result
    }
}

显示的代码:

最后的搜索结果 最后的搜索结果 上次搜索结果... 10 次

如果我将 async 更改为 false,它会正确显示: 第一个搜索结果 第二个搜索结果...等等

如果您使用的是 jQuery Ajax this could have been solved easily by using promises objects and $.when but as you said no library and also considering the mobiles, so you need to use the plain javascript promise ECMAScript 6 支持的对象。