简体   繁体   English

NodeJS-如果收到事件,则终止承诺链

[英]NodeJS - Kill promise chain if event received

I have series of promise chains, which took sufficient time to get completed. 我有一系列的承诺链,这花费了足够的时间来完成。 Below is the sample chain setup: 以下是示例链设置:

myJob1()
.then(myJob2)
.then(myJob3)
.then(myJob4)
.then(myJob5)
.then(myJob6)
.catch(myJobError);

In mean time when this job is running, if the person on UI think to cancel it, How can it be cancelled in whatever stage/function execution it is? 同时,在运行此作业的同时,如果UI上的人认为要取消该作业,那么无论其执行什么阶段/功能,如何取消该作业?

What can be the possible solution? 有什么可能的解决方案?

One alternative to modifying code for multiple job functions might be to check a user cancelled flag between jobs. 修改用于多个作业功能的代码的一种替代方法可能是检查作业之间的用户已取消标志。 If the granularity of this kind of checking is not too course, then you could asynchronously set a (somewhat) global cancelled flag and proceed along the lines of: 如果这种检查的粒度不太合适,那么您可以异步设置(有点)全局已取消标志并继续执行以下操作:

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

Don't forget that if you do check the cancelled flag inside a job, all you need to do is throw an error to have it bubble down the promise chain. 不要忘记,如果您确实检查了作业中的已取消标志,那么您要做的就是抛出一个错误,使它在承诺链中冒泡。

There is no way to cancel the promise (remember each of thens is returning a new promise) or clear the then callback. 无法取消承诺(记住thens每个都返回一个新的promise)或清除then回调。

Probably you are looking for something like redux-observable , where you can specify clause, until promise execution is actual. 可能您正在寻找类似redux-observable东西,您可以在其中指定子句,直到真正执行承诺为止。

See more in details: https://github.com/redux-observable/redux-observable/blob/master/docs/recipes/Cancellation.md 详细信息请参见: https : //github.com/redux-observable/redux-observable/blob/master/docs/recipes/Cancellation.md

As alternative I may only suggest you to create and manage some flag which determines whether further process is needed or not: 作为替代,我只建议您创建和管理一些标志,该标志确定是否需要进一步的处理:

// Inside each of promises in chain
if (notCancelled) {
    callAjax(params).then(resolve);
}

Or reject: 或拒绝:

// Inside each of promises in chain
if (cancelled) {
    // Will stop execution of promise chain
    return reject(new Error('Cancelled by user'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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