npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cancelable-promise

v4.3.1

Published

A simple cancelable promise

Downloads

128,560

Readme

cancelable-promise

GitHub license npm version Unit tests Cypress tests PRs Welcome

A simple Cancelable Promise.

This package is based on ES Promise.

  • See caniuse for browser support
  • See core-js for polyfills
  • For example, you can use https://polyfill.io/v3/polyfill.min.js?features=Promise%2CPromise.prototype.finally for Internet Explorer 11

FYI, you can cancel a fetch request with AbortController & AbortSignal.

Table of Contents

Install

npm install --save cancelable-promise

Usage

CancelablePromise acts like an ES Promise: you can use Promise.all, Promise.race with your CancelablePromise for example. The only difference is you'll have a cancel method on your promise to cancel future execution of then or catch functions. CancelablePromise will also cancel all callbacks attached to new promises returned by then/catch.

Basic example

import { cancelable, CancelablePromise } from 'cancelable-promise';

const promises = [
  cancelable(new Promise((resolve) => setTimeout(resolve, 1))),
  new CancelablePromise((resolve) => setTimeout(resolve, 1)),
];

for (const promise of promises) {
  promise.then(() => console.log('not logged'));
  promise.cancel();
}
// Nothing will be logged

NodeJS

const { cancelable } = require('cancelable-promise');
cancelable(new Promise((resolve) => resolve('ok')));

Browser

<script src="https://unpkg.com/[email protected]/umd/CancelablePromise.min.js"></script>
<script>
  const { cancelable } = window.CancelablePromise;
  cancelable(new Promise((resolve) => resolve('ok')));
</script>
<script type="module">
  import { cancelable } from 'https://unpkg.com/[email protected]/esm/CancelablePromise.min.mjs';
  cancelable(new Promise((resolve) => resolve('ok')));
</script>

API

cancelable

import { cancelable } from 'cancelable-promise';

/**
 * @param {Promise} arg - a native Promise
 * @returns {CancelablePromise}
 */
cancelable(
  new Promise((resolve) => {
    resolve('ok');
  })
);

CancelablePromise

import CancelablePromise from 'cancelable-promise';

/**
 * @param {(resolve, reject, onCancel) => void} arg - an augmented promise executor
 * @returns {CancelablePromise}
 */
const promise = new CancelablePromise((resolve, reject, onCancel) => {
  const worker = new Worker('some-script.js');

  onCancel(() => {
    worker.terminate();
  });

  worker.onmessage = (event) => resolve(event.data);
  worker.onerror = (error) => reject(error);
});

promise.cancel(); // It will execute the callback passed to onCancel

onCancel callback is working as in p-cancelable

cancelablePromise.cancel

/**
 * @returns {void}
 */
cancelablePromise.cancel();

cancelablePromise.isCanceled

/**
 * @returns {boolean}
 */
cancelablePromise.isCanceled();

cancelablePromise.finally

/**
 * @param {() => void} onFinally callback
 * @param {boolean} runWhenCanceled force finally execution on cancel
 * @returns {void}
 */
cancelablePromise.finally(() => {});

// You can release prematurely resources for a long running task
// by forcing finnaly callback execution when cancelling a promise
let worker;
const promise = cancelable(
  new Promise((resolve, reject) => {
    worker = new Worker('some-script.js');
    worker.onmessage = (event) => {
      resolve(event.data); // never executed
    };
    worker.onerror = (error) => {
      reject(error); // never executed
    };
  })
)
  .then(() => {
    console.log('never logged');
  })
  .finally(
    () => {
      console.log('executed');
      if (worker) {
        worker.terminate();
        worker = null;
      }
    },
    // runWhenCanceled boolean
    true
  );

promise.cancel();

Static methods

Same as Promise static methods.

import CancelablePromise from 'cancelable-promise';

CancelablePromise.resolve();
CancelablePromise.reject();
CancelablePromise.all([promise1, promise2]);
CancelablePromise.race([promise1, promise2]);
CancelablePromise.allSettled([promise1, promise2]);

You can still use the native Promise API and wrap your promise:

import { cancelable } from 'cancelable-promise';

cancelable(Promise.all([promise1, promise2]));
cancelable(Promise.race([promise1, promise2]));
cancelable(Promise.allSettled([promise1, promise2]));

CancelablePromise.isCancelable

Returns true if parameter is a cancelable promise.

import { cancelable, CancelablePromise } from 'cancelable-promise';

CancelablePromise.isCancelable(cancelable(new Promise(() => {}))); // true
CancelablePromise.isCancelable(new CancelablePromise(() => {})); // true
CancelablePromise.isCancelable(new Promise(() => {})); // false
CancelablePromise.isCancelable(undefined); // false
CancelablePromise.isCancelable({ cancel() {} }); // false

Utils

isCancelablePromise

Same as CancelablePromise.isCancelable, it returns true if parameter is a cancelable promise.

import {
  cancelable,
  CancelablePromise,
  isCancelablePromise,
} from 'cancelable-promise';

isCancelablePromise(cancelable(new Promise(() => {}))); // true
isCancelablePromise(new CancelablePromise(() => {})); // true
isCancelablePromise(new Promise(() => {})); // false
isCancelablePromise(undefined); // false
isCancelablePromise({ cancel() {} }); // false

Scripts

Build

Run babel

npm run build

Tests

Run eslint and jest

npm test

End-to-end tests

Run cypress tests

npm run test:e2e

Contributing

Feel free to dive in! Open an issue or submit PRs.

Contributors

This project exists thanks to all the people who contribute.

Code of conduct

Contributor Covenant Code of Conduct.

License

MIT License © Alkemics