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

@jrc03c/abortable-promise

v0.0.4

Published

This library offers an `AbortablePromise` class since regular ol' `Promise`s can't be aborted.

Downloads

150

Readme

Intro

This library offers an AbortablePromise class since regular ol' Promises can't be aborted.

Usage

Install:

npm install --save @jrc03c/abortable-promise

Import:

import { AbortablePromise } from "@jrc03c/abortable-promise"

The AbortablePromise class is a descendant of the Promise class, so you can use it wherever else you use Promises. But the AbortablePromise class adds roughly two new bits of functionality.

The first new bit of functionality can be seen in the function that's passed into the AbortablePromise constructor. Instead of passing into the constructor a function that can only receive resolve and reject arguments, you can now pass a function that can accept resolve, reject, abort, and onAbort arguments (all of which are functions). Like this:

new AbortablePromise((resolve, reject, abort, onAbort) => {
  try {
    // do the usual `Promise` stuff
    doSomethingHard().then(resolve)

    // but if you need to abort from inside this function, simply call `abort`
    if (somethingWentWrong) {
      abort(someReturnValue)
    }

    // you can also provide callbacks that'll be called when the
    // `AbortablePromise` has been aborted
    onAbort(someReturnValue => {
      // tidy up any loose ends, etc.
    })
  } catch (e) {
    reject(e)
  }
})

The second bit of new functionality can be seen from outside an AbortablePromise instance, specifically by calling the instance's abort and onAbort methods (which are exactly the same as the abort and onAbort functions seen above):

const promise = new AbortablePromise(...)

// add callbacks to be called when the `AbortablePromise` is aborted
promise.onAbort(someValue => {
  console.log(
    "The `AbortablePromise` was aborted and returned this value:",
    someValue
  )
})

// abort the `AbortablePromise` early if necessary
if (somethingWentWrong) {
  promise.abort(someValue)
}

If you abort an AbortablePromise, then any callbacks passed to the instance's then or catch methods will not be called. For example:

const promise = new AbortablePromise(...)

promise.onAbort(() => console.log("Abortion!"))

promise.then(() => {
  // because `promise` will be aborted below, this callback will not be called!
  console.log("Success!")
})

promise.catch(() => {
  // because `promise` will be aborted below, this callback will not be called!
  console.log("Failure!")
})

promise.abort()

Finally, here's one quite subtle point that I only learned while building this library: The then, catch, and finally methods of a Promise each return a new Promise, not the original Promise! So, chaining such calls like this:

fetch(...)
  .then(...)
  .catch(...)
  .finally(...)

...is actually equivalent to this:

const promise1 = fetch(...)
const promise2 = promise1.then(...)
const promise3 = promise2.catch(...)
const promise4 = promise3.finally(...)

I mention all of that because I specifically chose not to return a new AbortablePromise from the onAbort method. I found that including onAbort in chained method calls resulted in unexpected behavior, and I couldn't figure out how to make it behave in the expected way. Therefore, the onAbort method doesn't return anything and should not be chained. (If you know of a way to make chained calls to onAbort work correctly, I'd be glad to hear it!)

API

AbortablePromise(fn)

The AbortablePromise constructor accepts a function which receives four arguments, all of which are functions: resolve, reject, abort, and onAbort. For example:

new AbortablePromise((resolve, reject, abort, onAbort) => {
  // ...
})

Properties

wasAborted

A read-only boolean indicating whether or not the AbortablePromise was already aborted.

wasRejected

A read-only boolean indicating whether or not the AbortablePromise was already rejected.

wasResolved

A read-only boolean indicating whether or not the AbortablePromise was already resolved.

Methods

abort([...])

Aborts the AbortablePromise immediately and returns nothing. Any arguments passed into this function are automatically passed to all callback functions that were added via the onAbort method.

onAbort(fn)

Adds a callback function (fn) to the list of callback functions that will be called if the abort method is called. The function fn will automatically receive whatever arguments are passed into the abort method.

Examples

Here's an example of how you might implement your own function that returns an AbortablePromise:

function countToNSlowly(n) {
  return new AbortablePromise((resolve, reject, abort, onAbort) => {
    try {
      let counter = 0

      const interval = setInterval(() => {
        counter++
        console.log("Counter:", counter)

        if (counter >= n) {
          clearInterval(interval)
          resolve(counter)
        }
      }, 1000)

      // if the `AbortablePromise` gets aborted, then we need to be sure to shut
      // down the above loop
      onAbort(() => clearInterval(interval))
    } catch (e) {
      return reject(e)
    }
  })
}

const promise = countToNSlowly(10) // which should take 10 seconds

promise.then(() => {
  console.log("Done!")
})

promise.onAbort(() => {
  console.log("Aborted!")
})

// abort the counting early
setTimeout(() => promise.abort(), 3000)

A slightly more complex example involves wrapping the fetch function so that we can abort it if it's taking too long. This example is somewhat contrived because JS already provides the AbortController class that can be used in conjunction with fetch. But here it is anyway:

function abortableFetch(url, options) {
  options = options || {}

  return new AbortablePromise((resolve, reject, abort, onAbort) => {
    try {
      const controller = new AbortController()

      fetch(url, { ...options, signal: controller.signal })
        .then(response => resolve(response))
        .catch(error => reject(error))

      onAbort(() => controller.abort())
    } catch (e) {
      return reject(e)
    }
  })
}

const promise = abortableFetch("https://some-slow-website.com")

promise.then(response => {
  response.text().then(console.log)
})

promise.onAbort(() => {
  console.log("Aborted!")
})

// if we don't receive a response in 100ms, then we'll bail out!
setTimeout(() => promise.abort(), 100)