This question already has answers here:
How do I return the response from an asynchronous call?
                            
                                (38个答案)
                            
                    
                4年前关闭。
        

    

我在jQuery中的变量作用域遇到了一些麻烦,如果我在.each循环外执行console.log,在$ stockData上得到一个空数组怎么办? (如果我在.each内部执行此操作,则效果很好,每次添加值时都会记录该数组)

$(document).ready(function(){
    // stock data will contain all the merged data from the database and yahoo queries
    var $stockData = new Array();

    // get data from yahoo and merge with dbData, add to stockData array
    $.getJSON( "/get_portfolio.php", function(dbData) {
        $.each( dbData, function(index) {
            var stock = dbData[index]
            $.ajax({
                url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22"+stock.stock_symbol+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
                crossDomain: true
            }).success(function(data){
                var quote = data.query.results.quote;
                $.extend(quote, stock);
                $stockData.push(quote);
            }); // end success
        });// end each
    }); // end getJSON
    console.log($stockData);
}); // end document.ready

最佳答案

您打电话的时候

$.getJSON( "/get_portfolio.php", function(dbData) { ... });

这部分:

function(dbData) { ... }

不会立即运行。 JavaScript说:“哦,您发出了http请求?我将保留您提供给我的此函数,并在请求完成后运行它”。您的其余代码将继续运行,因此:

console.log($stockData);

将首先运行。因此,此处的实际执行顺序为:


您运行getJSON
console.log运行
HTTP请求完成,您的回调运行


.each循环之后,将console.log放入getJSON块中:

$(document).ready(function(){
    // stock data will contain all the merged data from the database and yahoo queries
    var $stockData = new Array();

    // get data from yahoo and merge with dbData, add to stockData array
    $.getJSON( "/get_portfolio.php", function(dbData) {
        var requestsDone = 0;
        $.each( dbData, function(index) {
            var stock = dbData[index]
            $.ajax({
                url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22"+stock.stock_symbol+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
                crossDomain: true
            }).success(function(data){
                var quote = data.query.results.quote;
                $.extend(quote, stock);
                $stockData.push(quote);
                if(++requestsDone == dbData.length) done();
            }).error(function(){
                if(++requestsDone == dbData.length) done();
            });
        });// end each
        function done() {
            console.log($stockData); // put this here
        }
    }); // end getJSON

}); // end document.ready

10-04 15:56
查看更多