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

p-signal

v5.0.0

Published

Better way to cancel promises using AbortSignal

Downloads

701

Readme

p-signal

Better way to cancel promises using AbortSignal

Gzipped Size Build Status

Install

npm install p-signal

Why

In the past few years, async implementations are on the rise. Canceling promises is an important part of working with async code. For example, a very common pattern is for a user task to be canceled or interrupted with the need to compute the latest value. However a good solution for cancelation doesn't exist (see Alternatives section for explanation). In this new async world p-signal can help.

Also:

  • Future-proof — based on AbortController and AbortSignal.
  • Cancellation as a technique can yield performance improvements because you don't continue executing the canceled task.
  • I've researched this topic for months. The solution looks simple, but it's a culmination of a lot of trial and error.
  • Supports browsers, React Native, Node 18+, Node 16 (if you polyfill AbortController), Deno.
  • I aim for high-quality with my open-source principles.

Usage

import { pSignal, isAbortError } from 'p-signal'

try {
    const result = await pSignal(AbortSignal.timeout(200), longRunningTask())
} catch (err) {
    if (isAbortError(err)) {
        // operation timed out
        return
    }
    
    throw err
}

async function longRunningTask() {
    return await parseText(currentFile.text)
}

API

pSignal<T>(signal: AbortSignal | undefined, value: Promise<T> | () => Promise<T>): T

Returns: T — the value returned by the promise or throws an error if the promise is rejected.

The first parameter accepts: AbortSignal or undefined. undefined as allowed type is useful for methods that accept an optional signal parameter:

function readFiles(files: string[], options: { signal?: AbortSignal }) {
    const result = []
    for (const file of files) {
        result.push(await pSignal(signal, readFile(file)))
    }
    return result
}

The second parameter accepts: a Promise, an asynchronous function, or a synchronous function that returns a Promise.

isAbortError(value: unknown): value is DOMException

Returns: boolean

Sometimes you care about errors but not about aborted actions. For example, you may want to send an error to an error tracking service but skip aborted actions (because they are expected).

import { pSignal } from 'p-signal'

try {
    await pSignal(signal, doHeavyWork())
} catch (err) {
    if (!isAbortError(err)) {
        sendToErrorTrackingService(err)
    }
}

The method also works for built-in abort errors. For example, when using fetch():

import { isAbortError } from 'p-signal'

try {
    fetch(url, {
        signal
    })
} catch (err) {
    if (!isAbortError(signal)) {
        sendToErrorTrackingService(err)
    }
}

Alternatives

For the past years I've experimented with different ways to cancel promises. Unfortunately, a perfect solution doesn't exist because the design of JavaScript asynchronicity has inherent problems. Here are two alternatives I was using before coming up with the idea of p-signal:

Cancelable promises. p-cancelable and Bluebird are possible repos that you can use to work with the concept of cancelable promises. Note that Bluebird last release was in 2019. I was using cancelable promises before getting the idea about pSignal, and it was a nice experience.

CAF. An elegant way to solve this problem. I recommend it if your codebase is in JavaScript. For TypeScript, it isn't ideal because it can't be correctly typed because it uses generators.

Related

  • p-cancelable — Create a promise that can be canceled
  • promise-fun — Promise packages, patterns, chat, and tutorials
  • CAF — Cancelable Async Flows (CAF)
  • Deno async — Async utilities for Deno