Icontem

Cancellable chain of promises: Run chains of actions based on asynchronous events

Recommend this page to a friend!
  Info   View files Documentation   Demos   View files View files (15)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2017-05-17 (17 hours ago) RSS 2.0 feedNot yet rated by the usersTotal: 32 This week: 5All time: 497 This week: 1Up
Version License JavaScript version Categories
cancellable-chain-of 1.0MIT/X Consortium ...6Language, EcmaScript 6
Description Author

This object can run chains of actions based on asynchronous events.

It can create a chain of actions to execute asynchronously using promises to execute different actions depending on the results.

The actions may be resolved or canceled by the promise callback code using functions of this object.

Innovation Award
JavaScript Programming Innovation award nominee
February 2017
Number 2
Handling asynchronous events may be hard to manage with regular callbacks. Depending on the results of the events you may need to execute different code. Promises facilitate the conditional handling of such events.

The package provides a solution that simplifies the cancellation of multiple promises chained to handle multiple conditional actions.

Manuel Lemos
  Performance   Level  
Name: Jeremy Judeaux <contact>
Classes: 1 package by
Country: China China
Innovation award
Innovation award
Nominee: 1x

Details

Cancellable Chain Of Promises

npm version Build Status

A library to write cancellable chain of promises.

This library is inspired by the This-Binding Syntax proposal. If you don't want to depend on this proposal, you can have a look at the [like-bind-operator]() library.

This library relies on the Cancellation proposal, and the prex implementation.

Examples

import { CancellationTokenSource } from 'prex';
import makeChain from 'cancellable-chain-of-promises';

const source = new CancellationTokenSource();
cancelButton.onclick = () => source.cancel();

// Write your asynchronous code:
const chain = makeChain(source.token);
const promise = chain.resolve()
  ::chain.then(doSomething)
  ::chain.then(doSomethingElse)
  ::chain.catch(handleError);

// If you cancel, the "promise" object will reject with an Cancelled error.

Using like-bind-operator

import { CancellationTokenSource } from 'prex';
import makeChain from 'cancellable-chain-of-promises';
import $ from 'like-bind-operator';

const source = new CancellationTokenSource();
cancelButton.onclick = () => source.cancel();

// Write your asynchronous code:
const chain = makeChain(source.token);
const promise = chain.resolve()
  $(doSomething)
  $(doSomethingElse)
  $(handleError);

// If you cancel, the "promise" object will reject with an Cancelled error.

Documentation

This library is still experimental and may change in future releases.

chain

The chain object contains.

makeChain: chain = makeChain(source.token)

Creates a chain object linked to a cancellation token.

chain.then: promise::chain.then(onFulfilled[, onRejected])

Similar to Promise.prototype.then. If the token is in a cancelled state, onFulfilled and onRejected will not be called, and the returned promise will reject with the Cancelled error.

chain.catch: promise::chain.catch(onRejected)

Similar to Promise.prototype.catch. If the token is in a cancelled state, onRejected will not be called, and the returned promise will reject with the Cancelled error.

chain.newPromise: chain.newPromise((resolve, reject) => {})

A Promise factory, that returns a rejected Promise if the token is cancelled, or construct a new Promise. The callback is not called is the token is cancelled.

chain.resolve: chain.resolve(value)

A function that returns a rejected Promise if the token is cancelled, or a Promise resolved with the given value.

chain.reject: chain.reject(value)

A function that returns a rejected Promise if the token is cancelled, or a Promise rejected with the given value.

Cancelled

An Cancelled is used to represent the cancellation of an operation. It is the rejected value to propagate the cancellation through a chain of promises.

Utility functions

always: (aliases: chain.always) promise::always(callback)

Use always to always call a callback in a chain of promises. The returned or thrown value

Other Examples

Check some examples in src/utils/.

Cancellable Request

const request = (url, { method, body, cancelToken = CancellationToken.none }) => {
  let registration;
  return new Promise(function (resolve, reject) {
    const xhr = new XMLHttpRequest();
    registration = cancelToken.register(() => {
      xhr.abort();
      reject(new Cancelled(cancelToken));
    });
    xhr.open(method, url);
    xhr.onload = function () {
      if (this.status >= 200 && this.status < 300) {
        resolve(xhr.response);
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      }
    };
    xhr.onerror = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };
    xhr.send(body);
  })::always(() => registration.unregister())
};

Cancel Operations When Removing a Widget

class Widget {
  constructor() {
  	this.source = new CancellationTokenSource();
    this.chain = makeChain(this.source.token);
  }

  destroy() {
    this.source.cancel();
  }

  onclick() {
    request('/random', {cancelToken: this.source.token})
      ::this.chain.then(response => this.updateState(response));
  }

  // other methods ...
}
  FiddleExternal page  
  Files folder image Files  
File Role Description
Files folder imagesrc (1 file, 1 directory)
Files folder imagetest (3 files)
Accessible without login Plain text file .babelrc Data Auxiliary data
Accessible without login Plain text file .editorconfig Data Auxiliary data
Accessible without login Plain text file .eslintignore Data Auxiliary data
Accessible without login Plain text file .eslintrc.json Data Auxiliary data
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file package.json Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  src  
File Role Description
Files folder imageutils (3 files)
  Plain text file index.js Class Class source

  Files folder image Files  /  src  /  utils  
File Role Description
  Accessible without login Plain text file cancelPreviousCalls.js Example Example script
  Accessible without login Plain text file setCancellableInterval.js Aux. Auxiliary script
  Accessible without login Plain text file setCancellableTimeout.js Aux. Auxiliary script

  Files folder image Files  /  test  
File Role Description
  Accessible without login Plain text file .babelrc Data Auxiliary data
  Accessible without login Plain text file test.js Example Example script
  Accessible without login Plain text file testUtils.js Example Example script

 Version Control Unique User Downloads Download Rankings  
 100%
Total:32
This week:5
All time:497
This week:1Up