我有一系列的承诺链,它们花了足够的时间来完成。下面是链设置示例:
myJob1()
.then(myJob2)
.then(myJob3)
.then(myJob4)
.then(myJob5)
.then(myJob6)
.catch(myJobError);同时,当此作业运行时,如果UI上的人员认为要取消它,那么在任何阶段/功能执行中如何取消它?
可能的解决方案是什么?
发布于 2017-08-21 21:27:10
修改多个作业功能的代码的一种替代方案可能是检查作业之间的用户取消标志。如果这种检查的粒度不是很合理,那么您可以异步设置一个(某种程度上)全局取消标志,并继续执行以下操作:
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);不要忘记,如果您确实检查了作业中的已取消标志,那么您所需要做的就是抛出一个错误,让它在promise链中冒泡。
发布于 2017-08-21 20:05:47
没有办法取消promise (记住,每个thens都返回一个新的promise)或清除then回调。
你可能正在寻找像redux-observable这样的东西,在那里你可以指定子句,直到promise execution是实际的。
更多详情请看: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'));
}https://stackoverflow.com/questions/45796488
复制相似问题