@marvinh/cancel-token
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

Simple async promise cancellation

Minimal implementation for cancel tokens, similar to AbortController, but without the event handling. Uses the throw keyword under the hood but throws a string to prevent expensive stack trace creation.

Installation

npm install @marvinh/cancel-token
# or
yarn add @marvinh/cancel-token

Usage

import { CancelController } from "@marvinh/cancel-token";

const controller = new CancelController();
const signal = controller.signal;

doSomethingAsync()
  .then(() => {
    if (signal.aborted) throw "Aborted";
    // do something else
  })
  .catch(err => {
    if (err === "Aborted") {
      console.log("was aborted");
    }
  });

The above can be simplified with a helper function:

import { CancelController, wrap } from "@marvinh/cancel-token";

const controller = new CancelController();
const signal = controller.signal;

wrap(doSomethingAsync(), signal).catch(err => {
  if (err === "Aborted") {
    console.log("was aborted");
  }
});

License

MIT, see the license file.

Readme

Keywords

none

Package Sidebar

Install

npm i @marvinh/cancel-token

Weekly Downloads

1

Version

1.0.1

License

MIT

Unpacked Size

9.39 kB

Total Files

11

Last publish

Collaborators

  • marvinhagemeister