2017-01-09 66 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