Hooks with callback, works like events but with async callbacks and in order
The easiest way to run asynchronous event functions with callback and execution order. Works like javascript events and is small and dont have dependencies
npm install --save simple-hooks-callback
// get hooks class
var Hooks = require('simple-hooks-callback');
// start new hook instance with new hooks list
var hooks = new Hooks();
// your function
function function1 (data, cb){
// do something ...
console.log('function1', data);
// then remember to call the callback
cb();
// or run **return cb(err);** if you want return error
}
function function2 (data, cb){
// do something ...
console.log('function2', data);
// timeout to simulate the async request
setTimeout(function(){
// then remember to call the callback
cb();
}, 1000);
}
// register one function to run on hook event
hooks.on('do-something', function1);
// register other function
hooks.on('do-something', function2);
// run all registered functions
hooks.trigger('do-something', { someData: 'someValue' }, function AfterAll (err){
if (err) throw err;
console.log('doneAll');
// all done
});
// un register the function1
hooks.off('do-something', function1);
Link: https://tonicdev.com/570d0017d5cdb01100394e1a/570d0017d5cdb01100394e1b
MIT © Alberto Souza