Make style control flow
Generally, callback hell problem arises when there is a bunch
of interdependent async computations. Rather then trying to emulate
sync control flow with verious funky utils we can be declarative
and specify not
HOW to compute, but
WHAT to compute. Let's consider the
def'a'return 'a'def'b'return 'b'def'c'return a + bdef'd'return a + c
Here we defined all our computations in a simplest possible form.
For a example we just said that
a + c. We didn't say that
d you should call method
c() and concatenate
their results. Such simplicity give us many prizes:
This project implements control flow showed in the above example.
var flow = require'make-flow'var fn = flowfndef'a'return 'a'fndef'b'return 'b'fndef'c'return a + bfneval'c'cshouldequal'ab'
.def method defines what is called a task.
Once the task and all it's dependencies were defined we can evaluate it with
Task may be async:
done is a special case name meaning node style callback.
You can also define dependencies explicitly:
fndef'c' 'a' 'b'return a + b
All computation results are stored as the properties of the flow object, so the following is true:
fnfoo = 'foo'fneval'foo'fooshouldequal'foo'
As you can see
.eval() clobbers object on which it is called and subsequent evals
do not trigger computations.
But we can reuse our definitions!
var json = flowdef'json'fsreadFile'config.json' donedef'object'return JSONstringifyjsonjsonrun // just Object.create(this) actuallyset'filename' name // the same as this.filename = nameeval'object' cb
Creating such functions is what
make-flow where designed for.
.fn() method which facilitates their creation a bit:
var readJson = flowdef'json'fsreadFile'config.json' donedef'object'return JSONstringifyjsonfnthisfilename = namethiseval'object' cb
We can also link computations from various runtime layers:
var app = flowapplayer'app' // mark current instance to be app levelappat'app'appdef'config'readJson'config.json' doneappdef'db'return require'monk'configconnection_stringappdef'session'dbloadSessionreqcookiesession doneappdef'user'dbloadUsersessionusername done// ...httpcreateServerapprunlayer'request'set'req' reqset'res' reseval'some task'
In the above example
db will be evaluated only once,
not for each incoming request.
Another way to attach a task to a certain level is:
appdef'level' 'name' fn
All error objects returned from
flowdef'foo'throw 'ups'eval'foo'err_taskshouldequal'foo'err_stackshouldequal'foo'flowdef'bar'flowdef'baz' throw 'ups'eval'baz' doneeval'bar'err_taskshouldequal'bar'err_stackshouldequal'bar.baz'
Everything is executed sequentially.
npm install make-flow
As a component
component install eldargab/make-flow
easy-app is a simple and powerful container with the same core ideas.