Skip to content

JS Cancellation Tokens for composable async cleanup in ES2015

Notifications You must be signed in to change notification settings

html-next/cancellation-token

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Cancellation Token

ES2015 JS Cancellation Tokens for composable async cleanup

Installation

yarn add cancellation-token

About

Tokens are extremely lightweight and easy to grok, their power lies in their composability. The entire implementation is this:

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

import Token from 'cancellation-token';

let token = new Token();

conditional work

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

let scheduledJob = schedule(() => { alert("hello world!"); });
scheduledJob.cancel();

inheritance

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();

About

JS Cancellation Tokens for composable async cleanup in ES2015

Resources

Stars

Watchers

Forks

Packages

No packages published