使用下划线 _.delay,如何停止未来的执行并提供用户状态

Using underscore _.delay, how do I stop future execution and provide user status

我需要缓慢地处理输入数组,在不达到服务器速率限制的情况下对每个元素进行异步调用。我可以用 underscore _.delay() 做我想做的大部分事情,但是我如何 (a) 如果用户决定放弃,我如何取消延迟执行,以及 (b) 显示包含当前索引的状态数组。

这是我目前所拥有的...

function processArray(array) {
    var processElement = function(element) {
        return doAsynch(element);  // asynch task returning a promise
    };

    _.each(array, function(element, index) {
        _.delay(processElement, index * 1000, element);
    });
}

function userDecidesToCancel() {
    // stuck here
}

如果用户决定取消,比如在我们到达元素 N 之前,我很乐意让 doAsynch(N-1) 完成,但我不想开始任何进一步的工作(对于 N > = 1).有办法吗?

此外,关于状态,我不知道如何优雅地展示我们完成了总共第 N 项,即我想说...

    _.each(array, function(element, index) {
        _.delay(processElement, index * 1000, element).then(function(result) {
            // how can I get the result here? I'd like to log status
            console.log("just did " + index + " " + result);
        });
    });

我可以将该日志消息的一部分放入 processElement 函数(记录结果的部分),但我还需要相对于数组长度的索引,以便显示进度百分比。我认为该索引的知识正确地属于 _.each 循环,而不是传递给 processElement 函数。

提前致谢。

Underscores 的 _.delay 函数只是包装了原来的 setTimeout。 所以你可以收集所有的超时,然后用 clearTimeout:

取消它们
var cancels = _.map(array, function(element, index) {
  return _.delay(processElement, index * 1000, element);
});

function cancel() {
  // you can also track the current element from processElement and cancel 
  // only the timeouts that follow that one, but it might be an overkill.
  _.each(cancels, function(cancel) {
    clearTimeout(cancel);
  });
}

不幸的是,对于当前的实现,我看不到从 processElement 获得承诺的方法。