🏊 swimmer 🏊
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
$ 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)
),
10
)
} catch (err, task) {
console.log(`Encountered an error with task: ${task}`)
throw err
}
console.log(res)
}
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 = [...]
const pool = createPool({
concurrency: 5,
tasks: urls.map(url => () => fetch(url))
})
pool.onError((err, task) => {
console.warn(err)
console.log(`Encountered an error with task ${task}. Resubmitting to pool!`)
pool.add(task)
})
pool.onSuccess((res, task) => {
console.log(`Task Complete. Result: ${res}`)
})
pool.onSettled(() => console.log("Pool is empty. All tasks are finished!"))
const doIntenseTasks = () => {
tasks.forEach(
url => pool.add(
() => fetch(url)
)
)
pool.throttle(10)
pool.stop()
pool.start()
otherUrls.forEach(
url => pool.add(
() => fetch(url)
)
)
pool.clear()
}
API
Swimmer exports two functions:
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.