Asynquence
Video Course on Real-Time HTML5 with Node.jstalking about nested callbacks: implicit trust, inverson of control, less flexibility
how to express the previous example as a sequence of things:
introducing his library asynquence
npm install asynquence asynquence-contrib
the contrib has the additional pluginsvar ASQ = require("asynquence");
require("asynquence-contrib");
<- don't need to attach to a variable, doesn't return anything (retursn null
)- read a file and wait for it to finish
- call a timeout and wait for it to finish (database simulation)
- send the contents out
refactor the previous code Asynchronous File IO
function delayMsg(done, contents){ // done is how asynquence works
setTimeout(function(){
done(contents);
}, 1000)
}
function readFile(filename){
var sq = ASQ();
fs.readFile(filename, sq.errfcb());
return sq;
}
function say(filename){
return readFile(filename)
.then(delayMsg);
}
in the code above, the interesting part:
function readFile(filename){
var sq = ASQ();
fs.readFile(filename, sq.errfcb());
return sq;
}
the
sq.errfcb()
does all the if
/ else
wrapping. It adapts a callback style to a flow control style (use promises style in an environment that is callback style)errfcb means "error first callback"
sq.then(function(done){
fs.readFile(filename,)
});