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

async-job-state

v0.1.0

Published

A small library to handle long-running async tasks.

Downloads

50

Readme

async-job-state github, npm

A small helper library for creating asynchronous tasks with reporting and remaining time estimation.

TODO: better readme

Usage

Simple usage:

import {
  // job execution
  collectAsyncJob,
  startAsyncJob,
  asyncJobStreamTransform,

  // job creation helpers:
  indefiniteAsyncJob,
  arrayMapAsyncJob,
  rangeAsyncJob,
  sleep,

  // useful types:
  type AsyncJobState,
  AsyncJobPhase,
} from 'async-job-state';

const customTestJob = async function*(state: AsyncJobState) {
  yield state.itemIndex * 2;
  if(state.itemIndex >= 5) return;
};

const state = startAsyncJob(customTestJob, {
  // optional delay between iterations
  delay: () => new Promise(r => setTimeout(r, 100)),
  onStart(state) {
    console.log('Job started at index:', state.itemIndex);
    return { myAdditionalStateProperty: 'test job!' };
  },
  onProgress(state, item) {
    console.log('Progress:', state.itemIndex, item);
    // do something with the item
  },
  onEnd(state) {
    console.log('Job ended at index:', state.itemIndex);
  }
});

console.log(state.myAdditionalStateProperty);
// cancel the job by setting state.cancelled = true

await state.donePromise;

// alternatively to startAsyncJob which returns the state, you can use:
const results = await collectAsyncJob(customTestJob, { /* options */ });

Common job helpers:

console.log(
  await collectAsyncJob(indefiniteAsyncJob((stop, state) => {
    // calling stop() will end the task after the current iteration
    if (state.itemIndex === 3) stop(); // you can `return stop()` instead to end the task immediately
    return state.itemIndex;
  }))
); // [0, 1, 2, 3]

console.log(
  await arrayMapAsyncJob(['a', 'b', 'c'], async (item, state) => {
    // callbacks can be async
    return await Promise.resolve(item.toUpperCase());
  })
); // ['A', 'B', 'C']

console.log(
  await collectAsyncJob(rangeAsyncJob(3, (item) => item * 10))
); // [0, 10, 20]


// stream status reporting
const { state, transform } = asyncJobStreamTransform({
  timingAverageWindow: 5,
  startImmediately: true, 
  // if startImmediately is not set to true, the job will only start automatically
  // when the first stream item is processed, but then first time measurement will be off
});

// optionally set state.totalItems for time remaining estimates.

const jobStream = stream.Readable.from(customTestJob()).pipe(transform);
// use your stream as usual, state will be updated on each processed item

Types:

enum AsyncJobPhase {
    NotStarted = 0,
    Started = 1,
    Ended = 2
}

interface AsyncJobState {
  itemIndex: number;
  itemsTotal: number | undefined;
  cancelled: boolean;
  readonly phase: AsyncJobPhase;
  readonly startDate: Date;
  readonly endDate: Date | null;
  readonly clock: DurationIntervalClock | null;
  readonly estimatedRemainingSeconds: number | undefined;
  readonly error: any;
  readonly donePromise: Promise<void>;
}

interface DurationIntervalClock {
  durationsSamples: number[];
  intervalSamples: number[];
  checkHasGoodAverage(q?: number): boolean;
  lastDuration: number | undefined;
  lastInterval: number | undefined;
  averageDuration: number | undefined;
  averageInterval: number | undefined;
}

interface AsyncJobOptions<T, StateEx = void> {
    delay?: () => Promise<any>;
    timingAverageWindow?: number;
    onStart?: (state: AsyncJobState) => StateEx;
    onEnd?: (state: ExtendedAsyncJobState<StateEx>) 
        => void | Partial<StateEx>;
    onProgress?: (state: ExtendedAsyncJobState<StateEx>, item: T) 
        => MaybePromise<void | Partial<StateEx>>;
}

type AsyncJob<R> = AsyncIterable<Awaited<R>, void, void>;
type AsyncJobFactory<R> = (state: AsyncJobState) => AsyncJob<R>;

function startAsyncJob<R, StateEx>(factory: AsyncJob<R> | AsyncJobFactory<R>, options: AsyncJobOptions<R, AsyncJobState, StateEx>): ExtendedAsyncJobState<StateEx>;

function collectAsyncJob<R, StateEx>(factory: AsyncJob<R> | AsyncJobFactory<R>, options?: AsyncJobOptions<R, AsyncJobState, StateEx>): Promise<R[]>;