javascript - Cancel a delayed Bluebird promise - Stack Overflow

How to reject a delayed Promise:const removeDelay = Promise.delay(5000).then(() => {removeSomething(

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

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
Share edited Mar 1, 2022 at 0:53 Bergi 667k161 gold badges1k silver badges1.5k bronze badges asked Sep 30, 2015 at 17:24 VB_VB_ 45.8k44 gold badges162 silver badges312 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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

Bluebird v3

import * as Promise from 'bluebird';
Promise.config({cancellation: true});

const delayPromise = Promise
    .delay(5000)
    .then(() => doSomething());

delayPromise.cancel();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744954317a4603104.html

相关推荐

  • javascript - Cancel a delayed Bluebird promise - Stack Overflow

    How to reject a delayed Promise:const removeDelay = Promise.delay(5000).then(() => {removeSomething(

    2天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信