A minimalist NodeJS module for callback buffering.
$ npm i --save cb-buffer
// Dependencies
const CallbackBuffering = require("cb-buffer");
// Create a new callback buffer
var cb = new CallbackBuffering();
// Callbacks a random unique number after 1 sec
function getUniqueRandomNumberAsync(callback) {
if (cb.check(callback)) { return; }
setTimeout(() => {
debugger
cb.done(Math.random());
}, 1000);
}
// Request the unique number few times.
// It should be unique, and generated once
getUniqueRandomNumberAsync(console.log);
getUniqueRandomNumberAsync(console.log);
getUniqueRandomNumberAsync(console.log);
getUniqueRandomNumberAsync(console.log);
// ... after one second
// => 0.3639475910458714
// => 0.3639475910458714
// => 0.3639475910458714
// => 0.3639475910458714
// After one second (after the random number is found)
// we request it again
setTimeout(() => {
getUniqueRandomNumberAsync(console.log);
// => 0.3639475910458714
}, 1000);
Creates a new instance of CbBuffer
.
The instance will contain methods documented below and the following fields:
buffer
(Array): An array of functions to be called.waiting
(Boolean): A flag representing the state of the buffer.is_done
(Boolean): A flag representing the done state (is done or not).args
(Array): The callback function arguments.
- CbBuffer The
CbBuffer
instance.
Use this function to append the new function and return
if needed:
if (cb.check(callback)) { return; }
- Function
fn
: The callback function.
- Boolean
true
if thw async function was called already.
Calls the provided function with the callback arguments.
- Function
fn
: The function to call.
CLears the callback array.
Resets the internal data.
Calls all the functions from the buffer.
Have an idea? Found a bug? See how to contribute.
If you are using this library in one of your projects, add it in this list. ✨
bible.js
—The Bible as a NPM module.cb-bufferify
—Convert any async function to a cb-buffer handler.image-parser
—An image parser that works.