取消延迟的蓝鸟承诺

取消延迟的蓝鸟承诺

本文介绍了取消延迟的蓝鸟承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何拒绝延迟的承诺:

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

仅凭承诺致电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:

我们可以这样使用它:

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

这篇关于取消延迟的蓝鸟承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 15:56