Cancellable Promises

mckabue

Kabue Charles

Posted on October 12, 2019

Cancellable Promises

I want to be able to cancel my promises, and am using something inspired by:

const makeCancelable = promise => {
    let rejectFn;

    const wrappedPromise = new Promise((resolve, reject) => {
        rejectFn = reject;

        Promise.resolve(promise)
            .then(resolve)
            .catch(reject);
    });

    wrappedPromise.cancel = () => {
        rejectFn({ canceled: true });
    };

    return wrappedPromise;
};

Usage:

const cancelablePromise = makeCancelable(myPromise);
// ...
cancelablePromise.cancel();

The solution above works, but i would like to improve it and am not willing to use bluebirdjs or Observables (well, at least not currently...)

I would want to have that as a prototype of the Promise object, so i could call cancel on any native promise.

Anyone willing to offer the simplest implementation direction?

💖 💪 🙅 🚩
mckabue
Kabue Charles

Posted on October 12, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Cancellable Promises
ask Cancellable Promises

October 12, 2019