Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

c-promise2

DigitalBrainJS537MIT0.13.12

Cancelable promise with progress capturing, pause, timeouts, signals, data flows and decorators support

promise, cancelable, cancellable, p-cancelable, timeout, progress, cancel, abortable, abort, AbortController, AbortSignal, async, signal, await, promises, generator, co, yield, reject, race, decorator, delay, break, suspending, wait, bluebird, deferred, react, setState, cancellation, aborting, close, closable, pause, task

readme

Build Status Coverage Status npm npm bundle size David Stars

CPromise2

This lib provides CPromise class - an advanced version of the built-in Promise that supports:

  • deep cancellation through rejection. All static methods like all/race/allSettled support cancellation.
  • all & allSettled method support concurrency limitation and generators as promise producers
  • advanced progress capturing
  • flat async code writing using generators/yield as an alternative of async/await
  • event data flows (upstream & downstream)
  • pause & resume ability
  • timeouts
  • retries
  • AbortController support (providing & subscribing for multiple signals sources)
  • atomic subchains - such chains will be completed if the execution has been started, even if its upper chain received a Cancel signal.

Installation :hammer:

npm:

$ npm install c-promise2

yarn:

$ yarn add c-promise2

CDN:

Quick start

  • Import CPromise class:
import { CPromise } from "c-promise2";
  • Use CPromise constructor instead of Promise. To terminate internal async tasks (timers, request, streams etc.) gracefully subscribe your cleanup handler with onCancel(handler):
const doTask = (ms)=>{
  return CPromise((resolve, reject, {onCancel})=>{
    const timer= setTimeout(resolve, ms, "myValue");
    onCancel(()=> clearTimeout(timer));
  });
}

const promise = doTask(1000).then(console.log);

Or/and turn generators to async functions with CPromise.promisify to write cancellable async code in flat style:

const doTask = CPromise.promisify(function*(ms){
  yield CPromise.delay(ms);
  return "myValue";
});

const promise = doTask(1000).then(console.log);
  • Call promise.cancel([reason]) to cancel pending promise chain by rejecting the deepest pending promise in the chain with a special CanceledError reason:
    promise.cancel("My bad");

Basic example

Building plain CPromise chains using then

Codesandbox Live Demo

import { CPromise } from "c-promise2";

const promise= new CPromise((resolve, reject, {onCancel, onPause, onResume})=>{
    onCancel(()=>{
        //optionally some code here to abort your long-term task (abort request, stop timers etc.)
    });
}).then(
    value => console.log(`Done: ${value}`), 
    (err, scope) => {
        console.warn(`Failed: ${err}`); // Failed: CanceledError: canceled
        console.log('chain isCanceled:', promise.isCanceled); // true
        console.log('promise isCanceled:', scope.isCanceled); // true
    }
);

console.log('isPromise:', promise instanceof Promise); // true

setTimeout(()=> promise.cancel(), 1000);

Log:

isPromise: true
Failed: CanceledError: canceled 
chain isCanceled: true
promise isCanceled: true

Writing flat code using generators

Codesandbox Live Demo

import { CPromise } from "c-promise2";

const sayHello = CPromise.promisify(function* (v) {
  for (let i = 0; i < 3; i++) {
    console.log(`Hello [${i}]`);
    yield CPromise.delay(1000);
  }
  return v + 1;
});

const p = sayHello(5)
  .then(function* (v) {
    console.log(`Then`);
    yield CPromise.delay(1000);
    return v + 1;
  })
  .then((v) => console.log(`Done: ${v}`));

// setTimeout(() => p.cancel(), 1000); stop trying

Abortable fetch with timeout

This is how an abortable fetch (live example) with a timeout might look like

function fetchWithTimeout(url, {timeout, ...fetchOptions}= {}) {
   return new CPromise((resolve, reject, {signal}) => {
      fetch(url, {...fetchOptions, signal}).then(resolve, reject)
   }, {timeout, nativeController: true})
}

const promise= fetchWithTimeout('http://localhost/', {timeout: 5000})
      .then(response => response.json())
      .then(data => console.log(`Done: `, data), err => console.log(`Error: `, err))

setTimeout(()=> promise.cancel(), 1000); 

// you able to call cancel() at any time to cancel the entire chain at any stage
// the related network request will also be aborted

Note

You can use the cp-fetch which provides a ready to use CPromise wrapper for cross-platform fetch API, or cp-axios wrapper for axios with powers of CPromise.

.then method behavior notes

The behavior of the method is slightly different from native Promise. In the case when you cancel the chain after it has been resolved within one eventloop tick, onRejected will be called with a CanceledError instance, instead of onFulfilled. This prevents the execution of unwanted code in the next eventloop tick if the user canceled the promise immediately after the promise was resolved, during the same eventloop tick.

Ecosystem

React

Data fetching

Backend

  • cp-koa - a wrapper for koa that adds cancellable middlewares/routes to the framework

Learn more

See CPromise wiki

API Reference

JSDoc autogenerated API Reference

License

The MIT License Copyright (c) 2020 Dmitriy Mozgovoy robotshara@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

changelog

Changelog

All notable changes to this project will be documented in this file. Dates are displayed in UTC.

Generated by auto-changelog.

v0.13.12

  • Fixed progress capturing support for CPromise.run method; d5fead1

v0.13.11

31 January 2022

  • Added support for signal filter parameter in onSignal method; 104654a

v0.13.10

31 January 2022

  • Fixed atomic support in generators context by the CPromise.run method; 2366f27

v0.13.9

29 January 2022

  • Improved progress throttling logic; 185dd8a
  • Fixed README.md; 1d741fe

v0.13.8

17 October 2021

v0.13.7

24 May 2021

  • Fixed retry method to catch sync errors; 14ddfb8

v0.13.6

24 May 2021

v0.13.5

21 May 2021

  • Added support for propagation pause and resume events; acc8995

v0.13.4

20 May 2021

  • Fixed version injection by the build flow; 7d03432
  • Fixed a bug due to which wrong values passed to the done event listeners on promise fulfill; 82964ed

v0.13.3

13 May 2021

  • Fixed a bug with determining the presence of a native AbortController; a5a1394

v0.13.2

12 May 2021

  • Fixed getFnType logic #2
  • Refactored to avoid using constructor names; 190747a

v0.13.1

8 May 2021

  • Added the ability for the all, race, allSettled methods to take into account the atomic type of the nested chain; 4008a2e

v0.13.0

7 May 2021

  • Removed CPromise.from method; b79f8c5

v0.12.5

5 May 2021

  • Fixed a bug with capturing the progress of a generator with nested chains; 7d1b6ae

v0.12.4

2 May 2021

  • Fixed @ReactComponent bug; 2d75308

v0.12.3

1 May 2021

  • Added the ability to omit the empty componentWillUnmount method while still being able to automatically cancel async routines on unmount; d5685d3

v0.12.2

29 April 2021

  • Added bindMethods and bindListeners options for the @ReactComponent decorator; 4e86048

v0.12.1

27 April 2021

  • Fixed finally method; 4239923
  • Added @rollup/plugin-json to the build flow; d9d5dcc

v0.12.0

26 April 2021

v0.11.11

21 April 2021

  • Fixed bug with context for onDone shortcut method; 95d1c01

v0.11.10

21 April 2021

  • Fixed promisify bug with scope passing to the original function; 5d6e32c

v0.11.9

20 April 2021

  • Improved toString() logic; 7876164

v0.11.8

19 April 2021

  • Fixed cancellation of the allSettled method; 6862b8f

v0.11.7

18 April 2021

  • Added decorator option for the .promisify method; 63e7895

v0.11.6

17 April 2021

  • Fix: improved .delay timer disposing logic; 4de5852

v0.11.5

17 April 2021

  • Added the ability for .delay to notify intermediate progress values; eb32ab5

v0.11.4

16 April 2021

  • Fixed bug with progress capturing of nested chains; 15c0c0c
  • Fixed npm docs script; f5ac87d
  • Added comparison table; 6fabc2d
  • Fixed README.md section with retry usage examples; 6640360
  • Fixed JSDoc types for the .toString(); e9a48d3

v0.11.3

13 April 2021

  • Fixed a potential bug with late internal event listeners appending; 6e3e0b2
  • Fixed build badge link; 1bbe995

v0.11.2

13 April 2021

  • Fixed a bug with _objectToCPromise that happens if the thing has nullable value; 7daa396

v0.11.1

13 April 2021

  • Updated auto-changelog config; 82aeccd
  • Fixed a bug with generator progress capturing, if onProgress listener was attached before the first yield; 8bb1161

v0.11.0

13 April 2021

  • Removed scope argument that was previously passed to generators as the last argument; e78b2d6

v0.10.8

13 December 2020

v0.10.7

12 December 2020

v0.10.6

10 December 2020

  • added weight, innerWeight and label options for the async decorator; 25a1d8d

v0.10.5

8 December 2020

v0.10.4

7 December 2020

v0.10.3

7 December 2020

  • Fixed a bug with cleaning internal timer; b1b91a1
  • Updated CHANGELOG.md; 459fdbf

v0.10.2

7 December 2020

  • Added @canceled decorator; 7b53ca3

v0.10.1

7 December 2020

v0.10.0

6 December 2020

  • Added decorators support; ed3be00
  • Updated readme; 5eb8611
  • Fixed async decorator anchor in the README; ab1e49c

v0.9.1

30 November 2020

  • Added generator support for the then method; ee41529
  • Refactored test for CPromise.all; 4f28354
  • Updated CHANGELOG.md; cfbe7cb

v0.9.0

29 November 2020

  • Improved cancellation logic to work properly with multi leaves chains; cef6c54
  • Updated CHANGELOG.md; 7b2ab2c

v0.8.2

28 November 2020

v0.8.1

28 November 2020

  • Made the promise executor optional; 50e6649

v0.8.0

27 November 2020

  • Added canceled method to catch CanceledError rejection; b5f1336
  • Added canceled method to catch CanceledError rejection; 3d87a7f

v0.7.6

26 November 2020

v0.7.5

26 November 2020

  • Fixed allSettled bug with options resolving; 3fc84c3

v0.7.4

26 November 2020

  • Improved isCanceled state for then method; 004f032

v0.7.3

25 November 2020

  • Fixed React example anchor; 7716058

v0.7.2

25 November 2020

v0.7.1

25 November 2020

v0.7.0

24 November 2020

v0.6.1

22 November 2020

v0.6.0

22 November 2020

v0.5.3

17 October 2020

v0.5.2

16 October 2020

  • Fixed docs; e75ec21
  • Fixed bug with promise cancellation for all method c3ab73f

v0.5.1

14 October 2020

  • Fixed bug with promise cancellation for all method 011ff3f

v0.5.0

13 October 2020

  • Added concurrency, mapper, signatures options for all method; bcb4e63

v0.4.2

25 September 2020

v0.4.1

24 September 2020

v0.4.0

20 September 2020

v0.3.2

17 September 2020

  • Introduced AsyncGeneratorScope class; 2d1f427

v0.3.1

15 September 2020

v0.3.0

15 September 2020

v0.2.1

14 September 2020

  • Fixed all and race methods to support iterable input; 6829b41

v0.2.0

13 September 2020

  • Updated README.hbs.md; 1a80ce5
  • Fixed pre-commit script; b6439f9
  • Added debounce option for scope.progress; 295d433
  • Updated README.hbs.md; cdaf10a
  • Added package size badges; f52b1fe
  • Fixed pre-commit script; f0ddee7
  • Updated package size badges; 8eec56c

v0.1.9

11 September 2020

v0.1.8

11 September 2020

v0.1.7

11 September 2020

  • Fixed timeout cancellation; 3238d79

v0.1.6

10 September 2020

v0.1.5

10 September 2020

v0.1.4

10 September 2020

  • Fixed prepublishOnly script; d1156b9

v0.1.3

10 September 2020

v0.1.2

10 September 2020

v0.1.1

10 September 2020