Cancellable Promises
Kabue Charles

Kabue Charles @mckabue

About: Poet; Entrepreneur; Philosopher; Genius Lateral Thinker; Software Architect; Created Library.co.ke

Location:
Kenya
Joined:
Sep 27, 2017

Cancellable Promises

Publish Date: Oct 12 '19
5 2

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?

Comments 2 total

  • Brad
    BradOct 12, 2019

    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?

  • Paul Melero
    Paul MeleroJul 22, 2020

    I would advise you against adding properties to native prototypes. As it can lead to prototype names clashes. Adding options to native prototypes is like creating global variables, but worse. ;P

    See what Eric Elliot says about it:

    github.com/ericelliott/speculation...

    Also, you might want to check that library ;)

    Aaand this one: npmjs.com/package/p-cancelable

    Is the one that got uses underneath.

Add comment