Giter VIP home page Giter VIP logo

p-signal's Introduction

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

p-signal's People

Contributors

astoilkov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.