for循环中的Ajax不会返回数组位置的正确值,尽管闭包绑定了当前值位置的范围

ajax in a for loop won't return a correct values in array position, despite closure binds scope of current value position

本文关键字:位置 闭包 范围 绑定 Ajax 循环 for 数组 返回      更新时间:2023-09-26

这个问题可能是[AJAX调用for循环won't返回值到正确的数组位置的副本-我正在应用Plynx的答案。

我的问题是闭包不会遍历循环中的所有元素。然而,浏览器的网络显示所有ajax调用都成功了。

ajax将返回与闭包传递的当前元素不匹配的数据。


我有一个id数组;当前ID由i在循环中的第1位给出;ajax调用应该在循环中处理当前ID并返回如下数据:

data[id] = {object}

由于闭包跳过了循环的某些i元素,因此提供给闭包的当前id (items[i])与返回的数据不匹配。

// ajax function test: it returns "data[key] = ..", where key === id
function fetchDecorator (id) {
  var loadurl = 'http://localhost/';
    return $.ajax({
    url: loadurl,
    type: 'GET',
    cache: true,
    async: true,
    dataType: 'jsonp',
    data: {
       id: id
     },
    jsonpCallback: 'onFetchComplete'
  });
};
// callback function for ajax response
function onFetchComplete(data) {
  console.log('is data fetched?', data);
  return data
}
//items is an array of numeric ids: [7955,943987,4834331,..]
    for (var i = items.length - 1; i >= 0; i--) {
        (function (i){
            var currentID = items[i];
// first test
            console.log('current i',i,'current id', currentID);
            fetchDecorator(items[i])
            .done(function(data){
// second test
                console.log('current i',i ,',current ID in items[i] is', items[i], 'actual ID is:', Object.keys(data));
            })
        })(i);
    };

测试结果:

(1)所有的i元素正在被处理:

current i 209 , current id 24159975
current i 208 , current id 30833420
current i 207 , current id 14778161
current i 206 , current id 5798582
...

你能帮我弄清楚为什么闭包不能处理所有的元素吗?

(2)一些i -th元素在闭包中被跳过(这里缺少208,207,205,204);返回的实际ID与当前ID不同:

current i 209, current ID in items[i] is 24159975, actual ID is: ["14778161"]
current i 206, current ID in items[i] is 5798582, actual ID is: ["5798582"]
current i 203, current ID in items[i] is 37369491, actual ID is: ["27962727"] ...

我需要确保闭包将处理所有元素并返回与当前i位置匹配的数据。

所以currentIDitems[i]都有正确的id,但是你从ajax调用收到的数据有错误:

current i 209 , current id 24159975
...
current i 209, current ID in items[i] is 24159975, actual ID is: ["14778161"]

可以看到,data有错误的数据。这绝对不是闭包的问题。

和一些项目被跳过的原因是因为done回调没有调用其中的一些,即一些ajax调用实际上失败。

我找到了一个解决方案,即避免将ajax对象传递给done()函数,并使用callback代替。

从概念上讲,我不明白为什么前面的代码会给出错误:如果您能帮助找出区别,我将很高兴。

@monstruash提出了之前代码中某些ajax调用可能失败的可能性。我也让jquery自己处理回调:jsonp = callback[http://api.jquery.com/jQuery.ajax/](jquery关于ajax的文档)

这是我所做的:

function fetchDecorator (id, callback) {
var loadurl = 'http://localhost/';
return $.ajax({
url: loadurl,
type: 'GET',
cache: true,
async: true,
dataType: 'jsonp',
data: {
   id: id
 },
jsonp: 'callback',
success: callback
});
};

// then, for each element, do something
// here I used a map() function, but you could use a loop too
// 'items' is an array of ids.
$.map(items, function( id, position ) {
                fetchDecorator(id, function(data){
                    console.log(id, items[position], data.query.pages);
                    // do something
                })
            });