取消延迟的Bluebird承诺

VB_*_*VB_ 2 javascript promise bluebird

如何拒绝延迟的承诺:

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
Run Code Online (Sandbox Code Playgroud)

sdg*_*uck 8

蓝鸟v3

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

取消工作不需要设置代码

只需要cancel一个承诺:

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

promise.cancel(); //=> "Promise cancelled"
Run Code Online (Sandbox Code Playgroud)

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

修改后的例子:

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

removeDelay.cancel();
Run Code Online (Sandbox Code Playgroud)

______

Pre Bluebird v3

看一下以下文档Promise#cancellable:

默认情况下,承诺不可取消.承诺可以标记为可取消.cancellable().如果未解决,可以取消可取消的承诺.取消承诺会传播到仍然未决的目标承诺的最远可取消祖先,并且在给定原因或CancellationError默认情况下拒绝该承诺.

我们可以像这样使用它:

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');
Run Code Online (Sandbox Code Playgroud)