【问题标题】:Anonymous callback in JavaScript not working properlyJavaScript 中的匿名回调无法正常工作
【发布时间】:2017-05-22 02:30:48
【问题描述】:

我正在尝试使用带有 JavaScript 的匿名回调来仅在另一个函数完成后运行一个函数。在第一个函数 getDisciplines() 中运行 $getJSON 调用,该调用需要在运行 getRounds() 函数之前完成。这是因为在通过另一个 $getJSON 返回关联的回合之前需要知道学科。

在代码的底部,您可以看到返回的 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]

【问题讨论】:

  • 调用callBack里面的成功callBack属于$.getJSON里面的getDisciplines
  • 太好了,成功了,谢谢!

标签: javascript callback getjson asynccallback


【解决方案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) {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多