Cancel a delayed Bluebird promise

自古美人都是妖i 提交于 2020-01-24 18:03:01

问题


How to reject a delayed Promise:

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

回答1:


Bluebird v3

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

no setup code required to make cancellation work

Simply call cancel on a Promise:

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

promise.cancel(); //=> "Promise cancelled"

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.

Revised example:

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

removeDelay.cancel();

______

Pre Bluebird v3

Take a look at the documentation for Promise#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.

We can use it like so:

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


来源:https://stackoverflow.com/questions/32872203/cancel-a-delayed-bluebird-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!