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

swimmer

v1.4.0

Published

An async task pooling and throttling utility for javascript.

Downloads

33,967

Readme

🏊‍ swimmer

David Dependancy Status npm package v npm package dm Join the community on Slack Github Stars Twitter Follow

An async task pooling and throttling utility for javascript.

Features

  • 🚀 3kb and zero dependencies
  • 🔥 ES6 and async/await ready
  • 😌 Simple to use!

Interactive Demo

Installation

$ yarn add swimmer
# or
$ npm i swimmer --save

UMD

https://unpkg.com/swimmer/umd/swimmer.min.js

Inline Pooling

Inline Pooling is great for:

  • Throttling intensive tasks in a serial fashion
  • Usage with async/await and promises.
  • Ensuring that all tasks succeed.
import { poolAll } from 'swimmer'

const urls = [...]

const doIntenseTasks = async () => {
  try {
    const res = await poolAll(
      urls.map(task =>
        () => fetch(url) // Return an array of functions that return a promise
      ),
      10 // Set the concurrency limit
    )
  } catch (err, task) {
    // If an error is encountered, the entire pool stops and the error is thrown
    console.log(`Encountered an error with task: ${task}`)
    throw err
  }

  // If no errors are thrown, you get your results!
  console.log(res) // [result, result, result, result]
}

Custom Pooling

Custom pools are great for:

  • Non serial
  • Reusable pools
  • Handling errors gracefully
  • Task management and retry
  • Variable throttle speed, pausing, resuming of tasks
import { createPool } from 'swimmer'

const urls = [...]
const otherUrls = [...]

// Create a new pool with a throttle speed and some default tasks
const pool = createPool({
  concurrency: 5,
  tasks: urls.map(url => () => fetch(url))
})

// Subscribe to errors
pool.onError((err, task) => {
  console.warn(err)
  console.log(`Encountered an error with task ${task}. Resubmitting to pool!`)
  pool.add(task)
})

// Subscribe to successes
pool.onSuccess((res, task) => {
  console.log(`Task Complete. Result: ${res}`)
})

// Subscribe to settle
pool.onSettled(() => console.log("Pool is empty. All tasks are finished!"))

const doIntenseTasks = async () => {
  // Add more tasks to the pool.
  tasks.forEach(
    url => pool.add(
      () => fetch(url)
    )
  )

  // Increase the concurrency to 10! This can also be done while it's running.
  pool.throttle(10)

  // Pause the pool
  pool.stop()

  // Start the pool again!
  pool.start()

  // Add a single task and WAIT for it's completion/failure
  try {
    const res = await pool.add(() => fetch('http://custom.com/asset.json'))
    console.log('A custom asset!', res)
  } catch (err) {
    console.log('Darn! An error...')
    throw err
  }

  // Then clear the pool. Any running tasks will attempt to finished.
  pool.clear()
}

API

Swimmer exports two functions:

  • poolAll - creates an inline async/await/promise compatible pool
    • Arguments
      • Array[Function => Promise] - An array of functions that return a promise.
      • Int - The currency limit for this pool.
    • Returns
      • A Promise that resolves when all tasks are complete, or throws an error if one of them fails.
    • Example:
  • createPool - creates an custom pool
    • Arguments
      • Object{} - An optional configuration object for this pool
        • concurrency: Int (default: 5) - The currency limit for this pool.
        • started: Boolean (default: true) - Whether the pool should be started by default or not.
        • tasks: Array[Function => Promise] - An array of functions that return a promise. These tasks will be preloaded into the pool.
    • Returns
      • Object{}
        • add(() => Promise, config{}) - Adds a task to the pool. Optionally pass a config object
          • config.priority - Set this option to true to queue this task in front of all other pending tasks.
          • Returns a promise that resolves/rejects with the eventual response from this task
        • start() - Starts the pool.
        • stop() - Stops the pool.
        • throttle(Int) - Sets a new concurrency rate for the pool.
        • clear() - Clears all pending tasks from the pool.
        • getActive() - Returns all active tasks.
        • getPending() - Returns all pending tasks.
        • getAll() - Returns all tasks.
        • isRunning() - Returns true if the pool is running.
        • isSettled() - Returns true if the pool is settled.
        • onSuccess((result, task) => {}) - Registers an onSuccess callback.
        • onError((error, task) => {}) - Registers an onError callback.
        • onSettled(() => {}) - Registers an onSettled callback.

Tip of the year

Make sure you are passing an array of thunks. A thunk is a function that returns your task, not your task itself. If you pass an array of tasks that have already been fired off then it's too late for Swimmer to manage them :(

Contributing

We are always looking for people to help us grow swimmer's capabilities and examples. If you have an issue, feature request, or pull request, let us know!

License

Swimmer uses the MIT license. For more information on this license, click here.