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

@jsenv/cancellation

v3.0.0

Published

Make async function cancellable

Downloads

876

Readme

cancellation

Make async function cancellable.

npm package github main workflow codecov coverage

Presentation

@jsenv/cancellation provides a pattern to make your code cancellable. It is an implementation of cancellation API proposal that does not provide 100% of the proposal.

Installation

npm install @jsenv/cancellation

createCancellationTokenForProcess

createCancellationTokenForProcess is a function returning a cancellation token cancelled just before process exits. Can be used to close a server before a process exists for instance.

import { createCancellationTokenForProcess } from "@jsenv/util"
import { startServer } from "somewhere"

const cancellationToken = createCancellationTokenForProcess()
const server = await startServer()
cancellationToken.register(() => {
  server.stop()
})

— source code at src/createCancellationTokenForProcess.js.

executeAsyncFunction

executeAsyncFunction receives an async function and calls it immediatly. By default it won't do anything special but you can control what happens during the function execution using catchCancellation and considerUnhandledRejectionsAsExceptions.

— source code at src/executeAsyncFunction.js.

catchCancellation

It is a boolean which is false by default. When enabled any cancellation error thrown during the function execution is catched and returned.

By default when a function is cancelled it throws a cancel error. Use catchCancellation to avoid the cancellation error to terminates Node.js process with exit code 1.

Without catchCancellation

import { createCancellationSource } from "@jsenv/cancellation"

const fn = async ({ cancellationToken }) => {
  cancellationToken.throwIfRequested()
}

const cancelSource = createCancellationSource()
cancelSource.cancel()

await fn({
  cancellationToken: cancelSource.token,
})
console.log("Hello")
> node --experimental-top-level-await file.js
CANCEL_ERROR: canceled because toto

With catchCancellation

import { createCancellationSource, executeAsyncFunction } from "@jsenv/cancellation"

const fn = async ({ cancellationToken }) => {
  cancellationToken.throwIfRequested()
}

const cancelSource = createCancellationSource()
cancelSource.cancel("toto")

await executeAsyncFunction(
  () =>
    fn({
      cancellationToken: cancelSource.token,
    }),
  {
    catchCancellation: true,
  },
)
console.log("Hello")
> node --experimental-top-level-await node.js
Hello

As you can see the cancellation error is ignored. You could use isCancelError to detect the cancellation like this:

import { isCancelError, executeAsyncFunction } from "@jsenv/cancellation"

const result = await executeAsyncFunction(
  () =>
    fn({
      cancellationToken: cancelSource.token,
    }),
  {
    catchCancellation: true,
  },
)
if (isCancelError(result)) {
  console.log("cancelled")
}

But in practice cancellation means you are no longer interested in the result of the function execution. In my experience I never needed to do that.

considerUnhandledRejectionsAsExceptions

It is a boolean which is false by default. When enabled, any unhandled rejection occuring during the function execution will throw the error and Node.js will exits with 1. This function is usefull in case Node.js was launched with unhandled rejection mode that is not strict but you want to force a strict behaviour during a function execution.

In other words any unexpected error ocurring during your function execution will throw even if Node.js process is not in strict mod regarding unhandled rejection.

Without considerUnhandledRejectionsAsExceptions

const fn = async () => {
  Promise.reject(new Error("toto"))
}

await fn()
> node --experimental-top-level-await file.js
(node:58618) UnhandledPromiseRejectionWarning: Error: toto

With considerUnhandledRejectionsAsExceptions

import { executeAsyncFunction } from "@jsenv/cancellation"

const fn = async () => {
  Promise.reject(new Error("toto"))
}

await executeAsyncFunction(fn, { considerUnhandledRejectionsAsExceptions: true })
> node --experimental-top-level-await file.js
Error: toto

— See Node.js documentation about unhandled rejections