2017-01-07 2 views
0

JavaScriptを使用した匿名コールバックを使用して、別の機能が終了した後にのみ関数を実行しようとしています。最初の関数getDisciplines()では、$ getJSON呼び出しが実行され、getRounds()関数が実行される前に完了する必要があります。関連するラウンドが別の$ getJSONで返される前にDisciplinesを知る必要があるためです。JavaScriptの匿名コールバックが正常に動作しない

コードの最後に、返されるconsole.logコマンドの順序が表示されます。 getDisciplines()が完全に終了する前にgetRounds()関数が実行されているということがわかります。これをどうすれば解決できますか?

var my_Upcomings = [] 
var roundsCreated = {} 
var my_RoundsList = [] 

getDisciplines("none", function() { 
console.log("check in getRounds will start") 
getRounds(); 
}); 

function getRounds(){ 
    console.log("start getRounds") 
    console.log("my input Upcomings array:", my_Upcomings) 
    for (var i = 0; i < my_Upcomings.length; i++) { 
     console.log("check in get Rounds for loop") 
     my_UpcomingIdString = my_Upcomings[i].poolId.toString() 
      my_roundsUrl = startUrl + tournamentUrl + "/rounds/" + my_UpcomingIdString 
       $.getJSON(my_roundsUrl, //output: {"1":"Round 1","2":"Round 2"} 
        function (json) { 
         my_CurrentRoundsCreated = json; 
         my_roundCount = Object.keys(my_CurrentRoundsCreated).length 
         my_Upcomings.roundsCreated = my_roundCount; 
         my_RoundsList.push(my_Upcomings.roundsCreated) 
         console.log(my_RoundsList) 
       }) 
    } 
} 

function getDisciplines(param, callback){ 
    console.log("Now in get Disciplines") 
    $.getJSON(listReadyMatchesUrl, function getUpcomingMatches (json) { 
     my_Upcomings = json 
     console.log("my upcoming matches", my_Upcomings) 
     my_Upcomings.roundsCreated = { 
        "roundsCreated": "0" 
       } 
    }) 
callback() 
} 

//console.log: 
    //Now in get Disciplines 
    //check in now rounds will start 
    //start getRounds 
    //my input Upcomings array: Array[0]length: 0__proto__: Array[0] 
    //my upcoming matches [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object] 
+0

は、成功コールバックの内側 'callBack'は' $ .getJSON'属するコール'getDisciplines'にあります。 –

+0

偉大な、これはトリック、ありがとう! – Jelle

答えて

1

コールバックの配置が間違っています。これが正しい方法です:

function getDisciplines(param, callback){ 
    console.log("Now in get Disciplines") 
    $.getJSON(listReadyMatchesUrl, function getUpcomingMatches (json) { 
     my_Upcomings = json 
     console.log("my upcoming matches", my_Upcomings) 
     my_Upcomings.roundsCreated = { 
        "roundsCreated": "0" 
       } 
    callback(); <-- Notice this line INSIDE the $.getJSON callback 
    }); 
} 

注:$ .getJSONのコールバックもこのように、匿名で次のようになります。 $.getJSON(listReadyMatchesUrl, function (json) {}

関連する問題