Cancel a delayed Bluebird promise
Asked Answered
P

2

2

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
Prerecord answered 30/9, 2015 at 17:24 Comment(0)
G
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');
Grizel answered 30/9, 2015 at 17:28 Comment(1)
this answer is outdated - refer to the documentation insteadFrau
A
0

Bluebird v3

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

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

delayPromise.cancel();
Ankle answered 1/3, 2022 at 0:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.