https://github.com/html-next/cancellation-token
JS Cancellation Tokens for composable async cleanup in ES2015
https://github.com/html-next/cancellation-token
Last synced: about 1 year ago
JSON representation
JS Cancellation Tokens for composable async cleanup in ES2015
- Host: GitHub
- URL: https://github.com/html-next/cancellation-token
- Owner: html-next
- Created: 2016-10-28T14:55:09.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2018-01-18T20:28:48.000Z (over 8 years ago)
- Last Synced: 2025-05-06T16:41:49.236Z (about 1 year ago)
- Language: JavaScript
- Homepage:
- Size: 2.93 KB
- Stars: 4
- Watchers: 1
- Forks: 1
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Cancellation Token
ES2015 JS Cancellation Tokens for composable async cleanup
## Installation
```cli
yarn add cancellation-token
```
## About
Tokens are extremely lightweight and easy to grok, their power lies in
their composability. The entire implementation is this:
```js
export default class Token {
constructor(parent) {
this._parent = parent;
this._cancelled = false;
}
get cancelled() {
return this._cancelled || (this._cancelled = this._parent ? this._parent.cancelled : false);
}
cancel() {
this._cancelled = true;
}
}
```
## Usage
Each example builds on the previous in order.
**create**
```js
import Token from 'cancellation-token';
let token = new Token();
```
**conditional work**
```js
let jobs = [];
function cancellableJob(job, token) {
return function() {
if (!token.cancelled) {
job();
}
};
}
function schedule(job) {
let token = new Token();
jobs.push(cancellableJob(job, token);
return token;
}
```
**cancelling work**
```js
let scheduledJob = schedule(() => { alert("hello world!"); });
scheduledJob.cancel();
```
**inheritance**
```js
let grandParentToken = new Token();
let parentToken = new Token(grandParentToken);
function scheduleWithParent(job, parentToken) {
let token = new Token(parentToken);
jobs.push(cancellableJob(job, token);
return token;
}
// cancel the task and all descendants
grandParentToken.cancel();
```