如何在 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"));
相关文章:
- 如何将一个JavaScript函数回调为多个函数
- JavaScript回调函数
- 用于回调的javascript参数
- Soundcloud Javascript SDK 3.0-回调无法读取属性'connectCallback
- Javascript点击事件回调不起作用
- 如何让程序员在javascript中实现正确的回调
- 从多个回调 javaScript 返回最终对象
- 如何使用传递参数回调 JavaScript 对象属性
- 可能从其他域弹出时回调 JavaScript
- 一个函数,它接受回调并创建只能调用一次的新版本的回调.Javascript
- 构造Javascript回调:Javascript/JQuery
- 对象成员函数的回调?(Javascript)
- 回调javascript动画
- 如何将自定义回调javascript参数添加到bing API回调中
- Facebook喜欢按钮回调javascript警告框
- 在Yii2中表单验证后的回调Javascript函数
- ASP.Net ThreadPool委托回调——JavaScript不会在回调线程上触发
- 其他函数中的回调 javascript 函数
- robot -递归回调- JavaScript
- 更好的回调Javascript代码在Express/NodeJs