Async Control
Help control parallel executions of async tasks/functions.
Install
npm i @zhaoyao91/async-control
Usage
Wrappers
Wrappers are composable high order functions which provide various async control options.
const {
returnError,
retry,
limitRate,
limitParallel,
expoBackoff
} = require("@zhaoyao91/async-control");
const wrappers = [
returnError(), // returning error instead of throwing
retry({
maxRetries: 3,
backoff: expoBackoff({
factor: 1000, // milliseconds
base: 3, // defaults to 2
min: 100, // milliseconds, defaults to 0
max: 1000 // milliseconds, defaults to Infinity
})
// backoff: constBackoff(...)
// backoff: linearBackoff(...)
}),
limitRate({
count: 100,
interval: 1000 // milliseconds
}),
limitParallel(500)
];
Run
You can build a run
function to run many tasks (async functions without arg) with controls.
const { buildRun } = require("@zhaoyao91/async-control");
const wrappers = ...
const tasks = ... // async function without arg
const run = buildRun(wrappers);
// const run = buildRun(...wrappers); // another api format
const results = await run(tasks);
// const results = await run(...tasks); // another api format
Wrap
You can wrap an existing async function to get a controlled version of it.
const { buildWrap } = require("@zhaoyao91/async-control");
const wrappers = ...
const wrap = buildWrap(wrappers);
// const wrap = buildWrap(...wrappers);
const myFetch = wrap(fetch);
const response = await fetch("https://github.com/zhaoyao91-npm");
API
Function Builders:
Wrappers:
Retry Backoffs:
Errors:
Note
buildWrap
Note about If you use the same wrap
functions to wrap multiple target functions, the wrapped functions will share the same suite
of wrappers (so the invocations of them would be controlled in the same limit queue, etc).
This logic is correct and intended, but should be put emphasis on to avoid misunderstandings.
If you need the wrapped function to be controlled separately, make sure build separate a suit of wrappers for each of them.
License
MIT