Published on

How to write a Cancelable Promise in JavaScript

Authors

Similar to that of AbortController we can cancel the promise before it finishes execution as well.

But unfortunately, we don't have a standard way to do it yet.

So we'll be relying on an external package p-cancelable

How does it work?

p-cancelable package provides a wrapper around Promise and adds a cancel method which we can use to cancel the promise anytime.

Example Snippet

We need to install the package first:

npm i p-cancelable
// ref: https://github.com/sindresorhus/p-cancelable
import PCancelable from "p-cancelable";

const cancelablePromise = new PCancelable((resolve, reject, onCancel) => {
  onCancel(() => {
    // This gets executed when cancelling the Promise
  });

  // You can either resolve it using "resolve()"

  // Or, reject it using "reject()"
});

// Cancel the operation after 10 seconds
setTimeout(() => {
  cancelablePromise.cancel("Cancelling the promise");
}, 10000);

try {
  console.log("✅", await cancelablePromise);
} catch (error) {
  if (cancelablePromise.isCanceled) {
    // Handle the cancellation here
    console.log("🔴");
    return;
  }

  throw error;
}

Happy cancelable promise!