2. Callback convention
Gergely Nemeth
● Blocking style?
○ bad performance
● Promises?
○ majority of Node libraries don’t support it out of the
box
How:
● error should be the first parameter
● the callback the last
3. Check for errors in
callbacks
Gergely Nemeth
● When not dealt with, may manifest itself elsewhere in
the code
graph.get(url, function (err, res) {
if (err) {
//deal with the error
}
//other stuff
});
4. Don’t use try-catch in
async code
Gergely Nemeth
1. exceptions won’t be caught
2. will bubble up to the top
3. can kill the entire process (if no uncaughtException is
set)
a. no meaningful context
b. not possible to respond appropriately
5. Return on callbacks
Gergely Nemeth
● Callbacks don’t halt execution when got hit
● Execution may continue even after a callback is called
getAccessToken = function getAccessToken(creds, done) {
//do things
return done();
});
};
6. Avoid this and new
Gergely Nemeth
● In node, passing around callback is common
○ bind to a specific context is not a win
● Prefer explicit arguments
● Use a more functional style
var myAsyncOperation = function (site, callback) {
Page.get(site, callback);
};
async.map(['echojs', 'nodejs'], myAsyncOperation, ...);
7. Use async.js
Gergely Nemeth
● control flow library (for node and the browser as well)
● each, series, parallel, waterfall... (more than 20 flows!)
async.waterfall([
function step1(callback){
callback( null, 'one', 'two');
},
function step2(arg1, arg2, callback){
callback( null, 'three');
},
function step3(arg1, callback){
// arg1 now equals 'three'
callback( null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
8. Praise the module
Gergely Nemeth
● simple module loading system
//app.js
var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '+ circle.area(4));
//circle.js
exports.area = function (r) {
return PI * r * r;
};
● cycles: to prevent infinite loops, Node uses unfinished
copies
● caching