0.2.1 • Published 8 years ago
async-machine v0.2.1
async-machine
minimal async finite state machine - tiny, powerfull, no dependencies, < 1kb min
• Example • Why • Limitations • API • License •
Example
var machine = require('async-machine')
function asyncAdd(v, cb) {
siteTimeout(cb, 0, ++v)
}
function syncAdd(v, cb) {
cb(++v)
}
function ondone(err, res) {
if (res < 10) this[0](res)
else console.log(res)
}
var sequence = machine([asyncAdd, syncAdd], ondone)
machine[0](0) // 10!
Why
This is a proof of concept async flow control module.
It is similar to async-waterfall
but with additional functionalities similar to a finite state machine:
- a sequence is defined once but can be run many times
- ability to move forward or back in the sequence at anytime
- change in state cancels any pending callbacks
This allows the following uses:
- run a sequence in steps (similar to
async-waterfall
) - run a sequence in a loop (
async-while
) - join branches together to form a more complex finite state machine
Limitations
- Every sequence runs in a single direction
- No configuration
- No named stated. Only the index in the sequence
API
machine(arrayOfAsyncFunctions, ondone)
=> return an array of functionsarrayOfAsyncFunctions
: any number of functions that pass a result to a callbackf(a , b, function(err, res))
callback
: node style error-first functionondone
: node style error-first function, internally binded to the array of steps
Any of the function returned in the array can be called at any time. Doing so cancels any pending callbacks.
All callbacks and the final ondone
function are binded to the sequence,
allowing for conditionally loop back or jump forward anywhere in the sequence.
License
Released under the MIT License