我有一系列的承诺链,需要足够的时间才能完成。以下是样本链设置:
myJob1()
.then(myJob2)
.then(myJob3)
.then(myJob4)
.then(myJob5)
.then(myJob6)
.catch(myJobError);
在这个作业运行的同时,如果UI上的人想要取消它,如何在任何阶段/功能执行中取消它?
可能的解决方案是什么?
答案 0 :(得分:1)
修改多个作业功能的代码的一种替代方法可能是检查作业之间的用户取消标记。如果这种检查的粒度不是太过分,那么你可以异步设置一个(某种程度上)全局取消的标志并继续沿着这样的行:
let userCancelled = false;
let checkCancel = function( data) {
if( userCancelled)
throw new Error( "cancelled by user"); // invoke catch handling
return data; // pass through the data
}
myJob1()
.then(myJob2).then( checkCancel)
.then(myJob3).then( checkCancel)
.then(myJob4).then( checkCancel)
.then(myJob5).then( checkCancel)
.then(myJob6).then( checkCancel)
.catch(myJobError);
不要忘记,如果您确实检查了作业中取消的标志,那么您需要做的就是抛出一个错误,让它在承诺链中消失。
答案 1 :(得分:0)
无法取消承诺(请记住每个人都会返回新承诺)或清除then
回调。
可能你正在寻找类似redux-observable
的东西,你可以指定子句,直到承诺执行是实际的。
详细了解详情:https://github.com/redux-observable/redux-observable/blob/master/docs/recipes/Cancellation.md
作为替代方案,我可能只建议您创建和管理一些标志,以确定是否需要进一步处理:
// Inside each of promises in chain
if (notCancelled) {
callAjax(params).then(resolve);
}
或拒绝:
// Inside each of promises in chain
if (cancelled) {
// Will stop execution of promise chain
return reject(new Error('Cancelled by user'));
}