Presenting Seq for Node.js
-
Upload
douglas-muth -
Category
Technology
-
view
630 -
download
3
description
Transcript of Presenting Seq for Node.js
PRESENTING:SEQ
Who I am: Douglas Muth
How to contact me: /
What I do: Software Engineer
ABOUT [email protected] @dmuth
...mostly.
Flow control in node.js. Node.js is a callback-heavy language.
Often, it looks like this:
Also known as "boomerang code"!
THE PROBLEM
db.query("SELECT ...", function(error, results) { if (!error) { db.query("UPDATE ...", function(error, results) { if (!error) { db.query("INSERT ...", function(error, results) { // Oh God, why? } } }); }});
That was easy!
SEQ 101INSTALLATION
$ npm install seq
"this()" is the callback which goes to the next block of code
SEQ 101USAGE
var seq = require("seq");
seq().seq(function() { db.query("SELECT ...", this);
}).seq(function(results) { db.query("UPDATE ...", this);
}).seq(function(results) { db.query("INSERT ...", this); // Pretty sweet!
});
SEQ 101WHEN THINGS GO WRONG
seq().seq(function() { db.query("SELECT ...", this);
}).seq(function(results) { this(new Error("Shake things up a little"));
}).seq(function(results) { // This will never run db.query("INSERT ...", this);
}).catch(function(error) { // I got this!
});
HOW TO SEQIT'S A TRAP!
seq().seq(function() { db.query("SELECT ...", this);
}).seq(function(results) { seq().seq(function() { // Do something
}).seq(function() { // Do something else // This won't go to the outer Seq this();
}).seq(function() { // This gets called by accident
});
}).seq(function(results) { // This will never run db.query("INSERT ...", this);
});
SEQ 101SAFE NESTING OF SEQ
seq().seq(function() { db.query("SELECT ...", this);
}).seq(function(results) { var cb = this; // this() by any other name.. seq().seq(function() { // Do something
}).seq(function() { // Do something else // This won't go to the outer Seq cb();
}).seq(function() { // This never gets called
});
}).seq(function(results) { // This gets called db.query("INSERT ...", this);
});
ADVANCED SEQvar fs = require('fs');var exec = require('child_process').exec;
var Seq = require('seq');Seq() .seq(function step1() { exec('whoami', this) }) .par(function step2(who) { exec('groups ' + who, this); }) .par(function step3(who) { fs.readFile(__filename, 'ascii', this); }) .seq(function step4(groups, src) { console.log('Groups: ' + groups.trim()); console.log('This file has ' + src.length + ' bytes'); });
Order of execution is as follows:step1()step2() and step3() are executed in parallelstep4() ONLY when step2() and step3() complete
EVEN MORE SEQProcess an array of elements:
forEach()seqEach()parEach()
Play around with "this": this.stackthis.varsthis.into(key)this.args
Not for the faint of heart, and WAY beyond the scope of thispresentation.
The Seq repo:
FURTHER READING
https://github.com/substack/node-seq/
Feel free to clone and add your own presentations based off of!
ON THE WEBhttps://github.com/dmuth/nodejs-presentations
template.html
QUESTIONS?