Cancellable Promises

github logo ・1 min read

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?

twitter logo DISCUSS (1)
markdown guide
 

First does the example work?

Second, what would you want to improve if it works?

Third, if it doesn't work, whats wrong with using the mentioned libraries instead? Yes we all use too many libraries, but there is always the argument of not re-inventing the wheel right?

Classic DEV Post from Jun 27

Jack Of All Trades or Master of One?

That age old question: how many pies should one have a thumb in?

Kabue Charles profile image
Poet; Entrepreneur; Philosopher; A genius Lateral Thinker; Software Architect; Creator of Library.co.ke;

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❀️