吊装或回调问题?在writeLog()之前完成(循环),但在完成之前完成日志写入

问题描述:

我试图循环播放一组队列以获取播放器数据并将数据传递给对象。我的ajax调用获取文件。在通过所有团队循环之后,我想用收集的数据编写日志。问题是,writeLog()立即调用 - 我认为 - 不等待循环完成。这是一个悬挂问题吗?回调问题?如何在for循环完成后重构我的代码以写入Log()?吊装或回调问题?在writeLog()之前完成(循环),但在完成之前完成日志写入

(function(){ 

$('#generate-report').on('click', function(){ 

    var logObj = { 
     playerCount: 0, 
     firstNameArray: [], 
     lastNameArray: [], 
     firstNameCharCount: 0, 
     lastNameCharCount: 0, 
     resultFirst: 0, 
     resultLast: 0, 
     freqReportFirst: "First name\n", 
     freqReportLast: "Last name\n", 
     freqObjFirst: {}, 
     freqObjLast: {},   
    } 

    var url = "http://feeds.nfl.com/feeds-rs/roster/"; 

    var teams = new Array("3800", "0200", "0325", "0610", "0750", "0810", "0920", "1050", 
          "1200", "1400", "1540", "1800", "2120", "2200", "2250", "2310", 
          "2700", "3000", "3200", "3300", "3410", "3430", "2520", "3700", 
          "3900", "4400", "4600", "4500", "2510", "4900", "2100", "5110" 
            ); 
    //var teams = new Array("3800"); // For testing 

    for(var i=0; i<teams.length; i++){ 
     console.log(teams[i]); 
     $.ajax({ 
      url: url + teams[i] + ".json", 
      type: 'GET', 
      success: function(response){ 
       processPlayerNames(response, logObj); 
      }, 
      error: function(response){ 
       console.log(response); 
      } 
     }); 
    }; 

    writeLog(logObj); 

}); 

})();

+0

它不是一个提升的问题,它不是一个回调的问题,这是一个不知道如何处理异步方法问题 –

+0

@sbaden'WRITELOG(logObj)'可以被之前的所有名为'$阿贾克斯( )'电话完成。 – guest271314

$.ajax()异步返回结果。你可以把$.ajax()呼叫到一个数组,然后用Promise.all().map()上承诺的对象数组,或者使用$.when()Function.prototype.apply().map()调用在.then()writeLog()链可变表示jQuery的承诺对象之前完成所有的异步任务与$.when()调用返回。

var requests = $.when.apply(null, teams.map(function(team) { 
    return $.ajax({ 
      url: url + team + ".json", 
      type: 'GET', 
      success: function(response){ 
       processPlayerNames(response, logObj); 
      } 
     }); 
})); 

requests.then(function() { 
    writeLog(logObj) 
}, function(response){ 
    console.log(response); 
}); 
+0

不知道我完全理解 - 它是严格的ajax的东西吗? – sbaden

+0

不,这是一个“如何处理异步代码”的东西 –

+0

@sbaden'$ .ajax()'异步返回结果。 'for'循环执行'$ .ajax()'而不用等待先前的调用完成。可以在完成一个或多个'$ .ajax()'调用之前调用'writeLog()'。请参阅[如何从异步调用返回响应?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call?) – guest271314