简体   繁体   中英

How to break a callback chain in JavaScript?

I am uploading multiple files from a browser and need to do so sequentially.

So I chain the next upload commencement from the previous upload completion callback.

It's simple and works just fine.

During the upload I display the progress to the user along with a cancel button.

If the user hits cancel I want to stop the entire callback chain.

How would I do that? Is there some mechanism in JavaScript to halt my callback chain?

OK here is an example of a callback chain in JavaScript. The question is, how to break it from a "cancel" button?

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()

On click of a cancel button, set a flag

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

change your doProcess to

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)
    }
}

You can also stop your waiting

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)
}

you can set the flag in the cancel button itself

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

and check this value

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM