如何在JavaScript中打破回调链?

时间:2016-03-17 08:36:46

标签: javascript callback

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

所以我从上一次上传完成回调链接下一个上传开始。

这很简单,效果很好。

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

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

我该怎么做? 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()

1 个答案:

答案 0 :(得分:1)

单击取消按钮,设置标记

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

将您的doProcess更改为

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"));
相关问题