iterable-backoff
v0.1.0
Published
Backoff generators usable as simple iterables
Downloads
3,537
Readme
iterable-backoff
Backoff generators usable as simple iterables
Install
Installation of the npm package:
> yarn add iterable-backoff
# Or
> npm install --save iterable-backoff
Usage
import { fibonacci } from "iterable-backoff";
async function fetch(url) {
for (const delay of fibonacci()
.toMs()
.take(5)) {
try {
return await got(url); // or any promise-returning HTTP lib
} catch (error) {
console.warn(error);
await Bluebird.delay(delay); // or any promise-returning timer
}
}
throw new Error("too many tries");
}
Generators
linear(slope = 1, intersect = 1)
power(power = 2)
fibonacci()
exponential(base = 2)
Methods
addNoise(factor = 0.1)
Add a noise to the sequence, proportional to the value (default is 10%).
Particularly useful when the backoff is used to wait access for a shared resource and you don't want multiple consumer retrying at the same time.
for (const delay of power().addNoise()) {
// ...
}
clamp(min, max)
Clamps the value within inclusive min
and max
bounds.
for (const delay of exponential().clamp(null, 10)) {
// ...
}
map(fn)
Applies a custom function to each value of the sequence.
Clamps the value within inclusive min
and max
bounds.
for (const delay of fibonacci().map(x => x / 2)) {
// ...
}
take(n)
Limits the sequence to at most n
values.
You usually want to use this if you do not want to keep retrying for ever.
for (const delay of power().take(10)) {
// ...
}
toMs()
Converts the sequence's values to milliseconds (from seconds).
for (const delay of exponential(3)
.take(10)
.toMs()) {
// ...
}
Development
# Install dependencies
> npm ci
# Run the tests
> npm test
# Continuously compile
> npm run dev
# Continuously run the tests
> npm run dev-test
# Build for production (automatically called by npm install)
> npm run build
Contributions
Contributions are very welcomed, either on the documentation or on the code.
You may:
- report any issue you've encountered;
- fork and create a pull request.
License
ISC © Julien Fontanet