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 🙏

© 2025 – Pkg Stats / Ryan Hefner

polling-service-manager

v1.0.0

Published

A TypeScript utility for managing asynchronous operations that require polling

Readme

PollingServiceManager

A TypeScript utility for managing asynchronous operations that require polling. It handles scenarios where:

  1. An initial service is triggered
  2. The status of the service must be checked repeatedly until completion
  3. The result from the completed operation is used to trigger a final operation

This pattern is common in scenarios like file processing, long-running calculations, or external service integrations where results are not immediately available.

Installation

npm install polling-service-manager

Usage

Basic Example

import { PollingServiceManager } from 'polling-service-manager';

// Create a manager for tracking order status
const orderStatusManager = new PollingServiceManager<string, OrderDetails, DisplayData>();

// Start a job to track an order
const jobId = orderStatusManager.startJob(
  // Step 1: Trigger the order check
  async () => {
    const response = await api.initiateOrderCheck(orderId);
    return response.checkId;
  },
  
  // Step 2: Poll until the check is complete
  async (checkId) => {
    const status = await api.getOrderCheckStatus(checkId);
    return {
      done: status.isComplete,
      result: status.isComplete ? status.orderDetails : undefined
    };
  },
  
  // Step 3: Process the final results
  async (orderDetails) => {
    return await api.prepareOrderDisplayData(orderDetails);
  },
  
  // Success callback
  (displayData) => {
    updateOrderStatusUI(displayData);
  },
  
  // Error callback
  (error) => {
    showErrorNotification("Failed to load order status", error);
  }
);

// Later, if needed
orderStatusManager.abortJob(jobId);

Multiple Manager Instances

You can create different manager instances for different domains:

// Delivery status manager
const deliveryManager = new PollingServiceManager();

// Order processing manager
const orderManager = new PollingServiceManager({
  pollingInterval: 10000, // Check less frequently
});

// Each can handle multiple jobs of their respective domains

Custom Error Handling

The library provides custom error classes for specific scenarios:

import { PollingError, PollingAbortError } from 'polling-service-manager';

// In your polling function
async function pollStatus(id: string) {
  const response = await fetch(`/api/status/${id}`);
  
  if (response.status === 404) {
    // Signal that this job should be aborted
    throw new PollingAbortError("Resource not found, aborting");
  }
  
  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }
  
  const data = await response.json();
  return {
    done: data.status === 'complete',
    result: data.status === 'complete' ? data.result : undefined
  };
}

API Reference

PollingServiceManager

class PollingServiceManager<T, U, V> {
  constructor(options?: PollingServiceManagerOptions);
  
  startJob(
    triggerFn: TriggerFn<T>, 
    pollFn: PollFn<T, U>, 
    completeFn: CompleteFn<U, V>,
    onComplete?: (result: V) => void,
    onError?: (error: Error) => void
  ): string;
  
  abortJob(jobId: string): boolean;
  
  abortAllJobs(): void;
  
  getJobState(jobId: string): JobState | null;
  
  cleanupJob(jobId: string): boolean;
  
  getAllJobs(): Array<{ id: string, state: JobState }>;
}

Options

interface PollingServiceManagerOptions {
  pollingInterval?: number;       // Default: 5000ms (5 seconds)
  maxRetryAttempts?: number;      // Default: 10
  logLevel?: string;              // Default: 'info'
}

Job States

enum JobState {
  PENDING = 'PENDING',
  POLLING = 'POLLING',
  COMPLETED = 'COMPLETED',
  FAILED = 'FAILED',
  ABORTED = 'ABORTED'
}

Function Types

type TriggerFn<T> = () => Promise<T>;
type PollFn<T, U> = (triggerResult: T) => Promise<{done: boolean, result?: U}>;
type CompleteFn<U, V> = (pollResult: U) => Promise<V>;

License

MIT