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

Delayed Ajax calls to same URL using same data

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

我使用 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,它将在 task1 上调用它,然后在 task2 上调用它。但是,尽管它使调用异步,但我不明白为什么它只执行 task2 两次。无法理解它。

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

您必须包装函数 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 中变量是 "hoisted"。引用 Mozilla:

"Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top."

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

所以应该重写为:

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

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