我正在从浏览器上传多个文件,需要按顺序上传。
因此,我将上一个上载完成回调中的下一个上载开始链接起来。
它很简单,而且效果很好。
在上传过程中,我向用户显示进度以及取消按钮。
如果用户点击取消,我想停止整个回调链。
我该怎么做?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
});
将您的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"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句