An asynchronous callback's flow controller, chaining async function callbacks. Async methods calling flow make easy. I use it in node.js server and webapp.
npm install chainjs --save
👬 👬 👬
Chainjs can be used in node.js or browser . Use in node as below:
var Chain = require('chainjs')
Chain(function (chain, data) {
// initialize
console.log(data) // --> {name: 'Chainjs'}
chain.next();
})
.then(function (chain) {
chain.nextTo('branchStep')
})
.then(function (chain, data) {
var count = chain.data('count' || 0)
if (count > 2) {
chain.next('thenStep')
} else {
setTimeout(function () {
chain.data('count', count ++).retry()
})
}
})
.branch('branchStep', function (chain) {
chain.next('branchStep')
})
.then(function (chain, from) {
if (from == 'branchStep') {
// do something
}
chain.next()
})
.final(function (chain, data) {
// do something when chain is ending
})
.start({name: 'Chainjs'})
Look at the diagram of above chain-flow:
Each step's handler has been passed the chain
instance as the first argument.
-
Global API
-
Instance API
Create a Chain instance.
- if arguments is not empty, it will be call .then() with arguments automatically.
- else If first param is type of
Array
, then first param will be passed as arguments.
Chain(func /*, ..., funcN*/);
// or
Chain([func, func1, funcN])
Define a chain step, if a then step has multiple functions, it need each function call chain.next() to goto next step.
Chain().then(funcA1, funcA2, funcA3).then(func1)
If first argument is type of Array
, that argument will be passed as arguments.
Chain.then([func, ..., funcN])
// equal to
Chain.then(func, ..., funcN)
Call current function once again (use for recursive).
var flag
Chain(function (chain, data) {
if (flag) {
return chain.next()
}
flag = true
chain.retry()
}).start('value')
Define a chain step, if a then step has multiple functions, it need any function of this step calling chain.next() only once to goto next step.
Chain(func).some(function (chain) {
setTimeout(function () {
chain.next()
}, 100)
}, function (chain) {
setTimeout(function () {
chain.next()
}, 1000)
}, function (chain) {
setTimeout(function () {
chain.next()
}, 500)
}).then(function () {
// this step will be run after 100ms.
})
If first argument is type of Array
, that argument will be passed as arguments.
Chain.some([func1, func2, ..., funcN])
// equal to
Chain.some(func1, func2, ..., funcN)
Define a chain step, call each handlers of this step in sequence. In this step, each function call chain.next() to call next function. In orders from left to right of arguments
Chain(func).then(func1).each(funcA1, funcA2, funcA3)
If first argument is type of Array
, that argument will be passed as arguments.
Chain.each([func1, func2, ..., funcN])
// equal to
Chain.each(func1, func2, ..., funcN)
Start running the chain, and could pass data to initial step.
Chain(function (chain, initData) {
}).then(func1).then(func2).start(initData);
Destroy the chain, mark the chain as ending and destroy local variable, but don't calling final funtions.
notice: after use chain.destroy(), the chain contiue execute current step handler, so use with return for stoping current step excution
Chain(func).then(function (chain) {
chain.destroy();
return;
}).start();
Go to next step
chain.next();
// pass params to next step handler
chain.next(data);
Define a branch step, only using chain.nextTo(branchName)
to goto branch step.
Call chain.next()
from last step will skip next branch step.
-------------o
| ↓
o----o----->o---->o---->o
Chain(function (chain) {
chain.nextTo('branchA')
chain.next()
}).then(function (chain) {
throw new Error('This step should not be called')
}).branch('branchA', function (chain) {
chain.next()
}).branch('branchB', function (chain) {
throw new Error('This step should not be called')
}).final(function (chain) {
// done
}).start()
Go to next branch.
Chain(function (chain) {
chain.nextTo('branchA')
}).then(function (chain) {
throw new Error('This step should not be called')
}).branch('branchA', function (chain) {
chain.next()
})
Notice: .nextTo() should not goto previous step
Chain(function (chain) {
chain.next()
}).branch('branchA', function (chain) {
chain.next()
}).then(function (chain) {
chain.nextTo('branchA') // will throw an error
}).start()
Waiting some time then call next step.Just a shortcut of setTimeout(function () {chain.next()}, time)
.
// pass params to next step handler
chain.wait(5000, data); // wait 5s then call next
End up chain steps, mark the chain as ending, for cross steps data sharing
chain.end();
// pass params to final handler
chain.end(data);
Define a final step, witch will be invoke after call chain.end() or all step of this chain is over.
Chain(function (chain) {
...
chain.end('ending initial step')
}).then(function (chain) {
...
chain.next('step 2 calling')
}).final(function (chain, data) {
console.log(data) // --> ending initial step
})
Saving data in current chain
// set data
chain.data('param', param);
// set multiple data in batch
chain.data({
'param1': param1,
'param2': param2,
'param3': param3
});
// get data
chain.data('param');
// get all data
var chainData = chain.data();
Turn a regular node function into chainjs thunk.
function handler1 (param, callback) {
callback(param + 'Chain through step1, ')
}
function handler2 (param, callback) {
callback(param + 'step2')
}
Chain()
.then(Chain.thunk(handler1))
.then(Chain.thunk(handler2))
.final(function (chain, data) {
console.log(data); // --> Initialize! Chain through step1, step2
})
.start('Initialize! ')
Binding "this" to specified ctx for all functions of each step of current chain.
Chain(function () {
console.log(this); // --> "abc"
})
.then(function () {
console.log(this); // --> "abc"
})
.context('abc')
.start()
npm test
The MIT License (MIT)
Copyright (c) 2013 guankaishe
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.