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

one-promise

v0.1.0

Published

A tiny utility for tracking the most recently created promise

Downloads

3

Readme

OnePromise

A tiny JavaScript utility for tracking the most recently created promise.

OnePromise is useful when you have an asynchronous task, that task could have multiple pending executions at the same time, but only the most recent execution of that task is significant. In other words, only one promise is the current promise, and any older promises should be ignored or handled differently when they complete.

Goals

  • Easily detect when a Promise is interrupted by a newer Promise
  • Simplify your isLoading state
  • Automatically abort fetch requests
  • Minimal interface that mimics Promise.then
  • Zero dependencies
  • Written in TypeScript
  • Tiny (less than 1 KB)

Installation

With npm:

npm install --save one-promise

Examples

OnePromise is probably best explained by just showing an example. So here is a typical usage example:

let currentDetails;
let isDetailsLoading = false;

// call onePromise once at setup time
// use the returned value as a "next promise" function
const nextDetails = onePromise({
  // optionally provide a callback to watch "is pending" status
  onChangeIsPending(isPending) {
    isDetailsLoading = isPending;
  },
});

async function loadDetails(id) {
  // call the "next" function returned from onePromise()
  const updated = await nextDetails(
    // fetchDetails returns a Promise
    fetchDetails(id),
    // `onFulfilled` callback similar to `Promise.then` but with an `isCurrent` argument
    (details, isCurrent) => {
      if (isCurrent) {
        // Yay! This is still the most recent call to `loadDetails`.
        currentDetails = details;
        return true;
      } else {
        // Shucks. `loadDetails` was called again so this value is outdated
        return false;
      }
    },
  );
  return updated;
};

Here is another example, this time using an AbortSignal and Fetch API:

const nextExample = onePromise();

nextExample(
  // An async function may be used instead of a Promise.
  // The callback requires `signal` which will be an `AbortSignal`.
  // The signal will automatically abort if interrupted by another call.
  async ({ signal }) => {
    // pass the signal to fetch
    const response = await fetch(`https://example.com/`, { signal });
    // the response body may also be aborted
    return await response.json();
  },
  (value, isCurrent) => {
    if (isCurrent) {
      console.log("Here's the latest", value);
    }
  },
  (err, _isCurrent) => {
    if (err instanceof OnePromiseAbortError) {
      // signal aborted
    } else {
      console.error("Something went wrong :(", err);
    }
  },
);

Why?

I wrote this library because I felt like I had to re-solve the same problem in every application that I work on, oftentimes more than once in the same application. The problem I'm talking about typically sounds like this:

I have a UI component that fetches data and displays it. It has a "loading" state and an "error" state for when the fetch fails. The specific data to be fetched may change based on inputs, and those inputs may change at any time.

These requirements raise a lot of corner cases where it is easy to introduce subtle bugs. Many libraries and frameworks provide some way of helping to implement this scenario, but I wanted something that is highly generalized, lightweight, and not specific to any framework.

What about RxJS?

Some will point to RxJS as the preferred solution for this. RxJS is awesome and you certainly can use RxJS to achieve these goals (particularly with the switchMap operator). But sometimes RxJS feels like buying a laptop when you just need a calculator. Promise is a simpler abstraction than Observable. OnePromise is an attempt to find an elegant solution to a specific problem while staying in the realm of promises, which are native to JavaScript.