取消延迟的蓝鸟承诺

编程入门 行业动态 更新时间:2024-10-23 01:54:28
本文介绍了取消延迟的蓝鸟承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何拒绝延迟的承诺:

const removeDelay = Promise.delay(5000).then(() => { removeSomething(); }); //Undo event - if it is invoked before 5000 ms, then undo deleting removeDelay.reject(); // reject is not a method

推荐答案

Bluebird v3

我们不再需要将Promise声明为可取消"(文档):

We no longer need to declare a Promise as 'cancellable' (documentation):

无需设置代码即可使取消生效

no setup code required to make cancellation work

仅凭承诺致电cancel:

const promise = new Promise(function (_, _, onCancel) { onCancel(function () { console.log("Promise cancelled"); }); }); promise.cancel(); //=> "Promise cancelled"

您可能已经注意到,cancel方法不再接受取消的原因作为参数.取消所需的逻辑可以在提供给onCancel的函数中声明,该函数提供给Promise构造函数执行器的第三个参数.或在finally回调中,因为取消Promise时也不会将其视为错误.

As you may have noticed, the cancel method no longer accepts the reason for cancellation as an argument. Logic required on cancellation can be declared within a function given to onCancel, the third argument given to a Promise constructor executor. Or within a finally callback, as it is also not considered an error when a Promise is cancelled.

修订示例:

const removeDelay = Promise .delay(5000) .then(() => removeSomething()); removeDelay.cancel();

______

Pre Bluebird v3

看看 Promise#cancellable 的文档:

Take a look at the documentation for Promise#cancellable:

默认情况下,诺言不可取消.可以用.cancellable()将一个承诺标记为可取消.如果无法解决,则可以取消可撤销的承诺.取消承诺会传播到仍待处理的目标承诺的最远可取消祖先,并以给定的原因拒绝该承诺,或者 CancellationError 默认为

By default, a promise is not cancellable. A promise can be marked as cancellable with .cancellable(). A cancellable promise can be cancelled if it's not resolved. Cancelling a promise propagates to the farthest cancellable ancestor of the target promise that is still pending, and rejects that promise with the given reason, or CancellationError by default.

我们可以这样使用它:

const removeDelay = Promise .delay(5000) .cancellable() // Declare this Promise as 'cancellable' .then(() => removeSomething()); .catch(err => console.log(err)); // => 'Reason for cancel' removeDelay.cancel('Reason for cancel');

更多推荐

取消延迟的蓝鸟承诺

本文发布于:2023-11-10 09:41:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575032.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:蓝鸟

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!