Nodeschool
Flow control with Streams & Promises
Trainers
Sequoia McDowell @_sequoia
Andrew Pasquale @apasquale
Jason Woofenden jasonwoof.com
Sponsors
Goals
Streams: What are they?
How are they different from any other event emitter?
Pipe
var filestream = fs.createReadStream(‘1337.zip’) filestream //readable
.pipe(decryptor) //transform
.pipe(decompressor) //transform
.pipe(parser) //transform
.pipe(process.stdout); //writable
$ decrypt l337.zip | gunzip | parse.sh
# implicitly “pipe” parse.sh to stdout
Streams: How do they work?
readablez.pipe(transformer).pipe(process.stdout)
Why use it
Promises: What are they
Callbacks
Promises
doAsync1(function(){
doAsync2(function(){
doAsync3(function(){
doAsync4(function(){
});
});
});
doAsync1()
.then(doAsync2)
.then(doAsync3)
.then(doAsync4);
Usage
printfile(name, callback){
readFile(arg.name, function(contents){
console.log(contents);
});
};
printfile(name){
promise = new Promise();
readFile(arg.name, function(contents){
promise.resolve(contents)
});
return promise;
};
How do we get to that second version?
printfile(name, callback){
readFile(arg.name, function(contents){
console.log(contents);
});
};
getfilecontents(name){
promise = new Promise();
readFile(arg.name, function(contents){
promise.resolve(contents)
});
return promise;
};
How do we get to that second version?
db.getUser(123) //--> user obj
//pass user obj to...
.then(getPrefs) //--> filename
//pass filename to...
.then(getFileContents) //--> contents
//pass contents to...
.then(console.log);
Getting started
install a lesson from nodeschool.io:� npm i -g stream-adventure� npm i -g promise-it-wont-hurt
Resources
Sequoia: @_sequoia
Andrew: @apasquale
Jason: jasonwoof.com