取消延迟的蓝鸟承诺

问题描述:

如何拒绝延迟的承诺:

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()将一个承诺标记为可取消.如果无法解决,则可以取消可撤销的承诺.取消承诺会传播到仍待处理的目标承诺的最远可取消祖先,并以给定的原因拒绝该承诺,或者

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