如何在 JavaScript 中打破回调链

How to break a callback chain in JavaScript?

本文关键字:回调 JavaScript      更新时间:2023-09-26

我正在从浏览器上传多个文件,需要按顺序上传。

因此,我将下一个上传开始与上一个上传完成回调链接在一起。

它很简单,效果很好。

在上传过程中,我向用户显示进度以及取消按钮。

如果用户点击取消,我想停止整个回调链。

我该怎么做? JavaScript 中是否有一些机制可以停止我的回调链?

好的,这里有一个JavaScript中回调链的例子。 问题是,如何将其从"取消"按钮中分离出来?

https://jsfiddle.net/jq7m9beq/

var filenamesToProcessQueue = ['v.jpg','w.jpg','x.jpg','y.jpg','z.jpg']
function finishedProcessing (filename) {
console.log('finished processing: ' + filename)
// processing finished for this file, start again by chaining to the next one
doProcessFiles()
}
function waitForEachFile (filename, callback) {
// wait a couple of seconds and log the filename
setTimeout(function(){ console.log('Waited 2 seconds for: ' + filename);callback(filename);}, 2000)
}
function doProcessFiles() {
// get next file to process and remove it from the queue at same time
filename = filenamesToProcessQueue.pop()
// if the file is undefined then the queue was empty
if (typeof filename !== 'undefined') {
console.log('Process ' + filename)
waitForEachFile(filename, finishedProcessing)
}
}
doProcessFiles()

单击取消按钮时,设置标志

var cancelFlag = false;
document.getElementById("cancelBtn").addEventListener("click", function(){
   cancelFlag = true;
   //other code
});

将您的操作过程更改为

function doProcessFiles() 
{
    if (cancelFlag)
    {
      return false; //this will break the chain
    }
    // get next file to process and remove it from the queue at same time
    filename = filenamesToProcessQueue.pop()
    // if the file is undefined then the queue was empty
    if (typeof filename !== 'undefined') 
    {
       console.log('Process ' + filename)
       waitForEachFile(filename, finishedProcessing)
    }
}

您也可以停止等待

function waitForEachFile (filename, callback) 
{
    if (cancelFlag)
    {
        return false; //this will stop waiting as well
    }
   // wait a couple of seconds and log the filename
   setTimeout(function(){ console.log('Waited 2 seconds for: ' +   filename);callback(filename);}, 2000)
}

您可以在取消按钮本身中设置标志

document.getElementById("cancelBtn").setAttribute("data-flag", "true");

并检查此值

var cancelFlag = Boolean(document.getElementById("cancelBtn").getAttribute("data-flag"));