【问题标题】:NodeJS - Kill promise chain if event receivedNodeJS - 如果收到事件,则终止承诺链
【发布时间】:2018-01-29 11:48:17
【问题描述】:

我有一系列的承诺链,需要足够的时间才能完成。以下是示例链设置:

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

在此作业运行的同时,如果 UI 上的人想取消它,如何在它的任何阶段/功能执行中取消它?

可能的解决方案是什么?

【问题讨论】:

  • 真的需要更多信息,例如。尤其是当您说客户时。您的客户端是否有某种形式的 RPC?取消 Promise 链很容易,但将命令发送到后端是棘手的部分。
  • 您无法取消,但可以拒绝。这将阻止 then 的其余部分被调用。您必须在每项工作中测试某些内容,如果该测试通过,您将返回一个新的拒绝承诺,即return Promise.reject('reason')

标签: javascript node.js promise cancellation


【解决方案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);

不要忘记,如果您确实检查了作业中的取消标志,您需要做的就是抛出一个错误,让它在承诺链中冒泡。

【讨论】:

    【解决方案2】:

    没有办法取消承诺(记住每个 then 都返回一个新的承诺)或清除 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'));
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 2015-09-05
      • 2018-11-03
      • 1970-01-01
      • 2015-12-17
      • 2020-04-24
      • 2018-01-02
      • 2015-01-20
      相关资源
      最近更新 更多