JavaScript 中的匿名回调无法正常工作

Anonymous callback in JavaScript not working properly

我正在尝试使用匿名回调 JavaScript 到 运行 一个函数,只有在另一个函数完成后。在第一个函数 getDisciplines() 中,$getJSON 调用是 运行,它需要在 getRounds() 函数是 运行 之前完成。这是因为在通过另一个 $getJSON 返回关联的轮次之前需要知道纪律。

在代码的底部,您可以看到返回的 console.log 命令的顺序。我可以看到问题是 getRounds() 函数在 getDisciplines() 完全完成之前 运行ning。我该如何解决?

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]

您的回调位置有误。这是正确的方法:

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