嵌套在for循环中的getJSON块仅在最后一次迭代中执行[复制]

问题描述 投票:1回答:1

这个问题在这里已有答案:

我有这个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用于i,但它随机打印i的值,而不是顺序打印。它还会打印两次值。

为什么会这样?如何让内部块打印i在for循环期间所需的所有值?

javascript jquery
1个回答
0
投票

我认为在调用回调时是经典问题,如同在类似问题中提到的那样,您是否尝试将匿名函数放入循环中?而不是使用让?

$.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);
        }

});

© www.soinside.com 2019 - 2024. All rights reserved.