使用相同的数据延迟Ajax调用相同的URL

Delayed Ajax calls to same URL using same data

本文关键字:调用 URL Ajax 延迟 数据      更新时间:2023-09-26

在等待后端开发人员执行"取消所有"功能(即取消后端跟踪的所有任务)时,我试图通过取消每个单独的任务来临时解决这个问题。取消REST服务接受数据对象{transferID: someID}形式的ID。

使用FOR循环遍历存储在其他地方的id数组。预计人们最终可能会有几十个或几百个任务,我想实现一个小延迟,理论上不会超过浏览器可以处理的HTTP请求数量,也会减少后端CPU的负载。下面是一些带有注释的代码,用于讨论:

ta.api.cancel = function (taskArray, successCallback, errorCallback) {
// taskArray is ["task1","task2"]
// this is just the latest attempt. I had an attempt where I didn't bother
// with this and the results were the same. I THOUGHT there was a "back image"
// type issue so I tried to instantiate $.ajax into two different variables.
// It is not a back image issue, though, but one to do with setTimeout.
ta.xhrObjs = ta.xhrObjs || {}; 

for (var i = 0; i < taskArray.length; i++) {
    console.log(taskArray); // confirm that both task1 and task2 are there.
    var theID = taskArray[i];
    var id = {transferID: theID}; // convert to the format understood by REST
    console.log(id); // I see "task1" and then "task2" consecutively... odd,
    // because I expect to see the "inside the setTimeout" logging line next
    setTimeout(function () {
      console.log('inside the setTimeout, my id is: ')
      console.log(id.transferID);
      // "inside the setTimeout, my id is: task2" twice consecutively! Y NO task1?
      ta.xhrObjs[theID] = doCancel(id);
    }, 20 * i);
  }
  function doCancel(id) {
    // a $.Ajax call for "task2" twice, instead of "task1" then "task2" 20ms
    // later. No point debugging the Ajax (though for the record, cache is
    // false!) because the problem is already seen in the 'setTimeout' and
    // fixed by not setting a timeout.
  }
}

问题是:我知道setTimeout使包含函数异步执行。如果我去掉超时,在迭代器中调用doCancel,它会在task1task2上调用它。但是,虽然它使调用异步,我不明白为什么它只是做task2两次。

我正在寻找一种方法,让迭代器使Ajax调用延迟20ms。但我需要它来召唤两个人!有人看到我可以修复的明显错误吗,或者知道一种技术吗?

必须包装setTimeout函数并将id变量传递给它,如下所示:

(function(myId, i) {
    setTimeout(function () {
        console.log('inside the setTimeout, my id is: ', myId);
    }, 20 * i);
}(theId, i));

这个模式并没有为每个循环实例创建一个唯一的variable1

function () {
    for (var i = 0; i < length; i++) {
        var variable1;
     }
}

在javascript中变量被"提升"。引用Mozilla:

"因为变量声明(和一般的声明)是在执行任何代码之前处理,在任何地方声明一个变量在代码中相当于在顶部声明它。"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

所以应该重写为:

function () {
    var variable1;
    for (var i = 0; i < length; i++) {
    }
}

这意味着在循环结束后,引用该变量的任何异步回调都将看到循环的最后一个值。