2017-01-09 62 views
-1

我有以下的javascript代码,问题是,首先执行的功能getBestMovies4BestPCRating();amovies.forEach(function(item) {的Javascript的onreadystatechange函数调用优先

任何主意?

document.getElementById('sendMovies').addEventListener('click', function() { 
    var movieIDs = document.getElementById('MovieIDs').value; 
    var data = {}; 
    var amovies = {}; 
    var movies = {}; 

    data["movieList"] = '[' + movieIDs + ']'; 

    params = JSON.stringify(data); 

    var http = new XMLHttpRequest(); 

    var url = "http://............." 
    http.open("POST", url, true); 

    //Send the proper header information along with the request 
    http.setRequestHeader("Content-type", "application/json"); 

    http.onreadystatechange = function() { //Call a function when the state changes. 
     if (http.readyState == 4 && http.status == 200) { 
      movies = http.responseText; 
      amovies = JSON.parse(movies); 

      amovies.forEach(function(item) { 
       if (item.rating > 4) { 
        getEntitiesRatings(item.ratingsPK.userId, 0); 
       } 
      }); 
      getBestMovies4BestPCRating(); 
      convertmovies2table(bestMovies); 
     } 
    } 
    http.send(params); 

}); 

function getEntitiesRatings(userid, kind) { 

    var xmlhttp = new XMLHttpRequest(); 
    var url = " http://.............entities.ratings/" + userid; 

    xmlhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      var myArr = JSON.parse(this.responseText); 
      if (kind == 0) { 
       computeUserColleration(myArr, userid); 
      } 
      if (kind == 1) { 
       bestUserMovies(myArr, userid); 
      } 
     } 
    }; 
    xmlhttp.open("GET", url, true); 
    xmlhttp.send(); 

} 
+0

您的'getEntitiesRatings'函数是异步的。它们在'getBestMovies4BestPCRating'运行之前* ran *,但直到之后才完成。 –

+1

我看不到最佳影片分配在哪里?但是Hazmat是正确的,你要旋转你的数组并开始一堆Ajax请求,然后尝试将结果作为一个数组处理,而不知道所有请求都已完成,并且数组已完全分配。 –

回答

1

这些函数按照您编写的顺序执行。但是,第一个函数是异步的,所以结果不会立即可用。

考虑使用Promise来代替。

另外,下次尝试提供一个最小示例。代码中不需要这个集群来表达你的麻烦。

+0

可能是一个例子吗? – Giorgos