嵌套在for循环中的getJSON块仅在上一次迭代中执行

时间:2019-04-22 14:16:06

标签: javascript jquery

我有以下javascript代码:

$.getJSON(url, function(data) {     //Make a call to an api with the a url. 

    // Take the Response field of the json response. 
    // This field contains objects
    var d = data['Response'];             

    for(var i = 0; i < d.length; i++) {     // For each object
        var obj1 = d[i];                    
        var id = obj1['id'];            // Take the id of the object

        var url2 = endpoint+'id='+id                     

        // Make a new api call based on the id of the object
        $.getJSON(url2, function(obj2) {
            console.log(i)
        });
    }
});

由于某些原因,它仅打印i的最后一个值。虽然,当我在内部块外部和i块内部打印for的值时,它会打印i的所有值。

我还尝试使用let代替var的{​​{1}},但是它随机打印i的值,而不是顺序打印。它还会两次打印一些值。

为什么会这样? 如何在for循环中使内部块打印i所取的所有值?

1 个答案:

答案 0 :(得分:0)

我认为调用回调时是经典问题,如 您是否曾尝试将匿名函数放入循环中类似的问题? 而不是使用let?

$.getJSON(url, function(data) {     //Make a call to an api with the a url. 
        var d = data['Response'];             //Take the Response field of the json response. This field contains objects

        for(var i = 0; i < d.length; i++) {     //For each object
          (function(i) { // protects i in an immediately called function 
          var obj1 = d[i];                    
            var id = obj1['id'];            //Take the id of the object

            var url2 = endpoint+'id='+id
            $.getJSON(url2, function(obj2) {                     //Make a new api call based on the id of the object
                console.log(i)
              });
           })(i);
        }

});