Skip to content

Instantly share code, notes, and snippets.

@tranphuoctien
Forked from krazylearner/DesignPattern.js
Created March 21, 2016 10:17
Show Gist options
  • Save tranphuoctien/12ba68fa1a05e14bea8e to your computer and use it in GitHub Desktop.
Save tranphuoctien/12ba68fa1a05e14bea8e to your computer and use it in GitHub Desktop.
nodejs
// Pattern
//Usually, you call a callback as the last thing you do inside a function.
//You might consider it synonymous with return, only JavaScript does
//not halt function execution when it hits it. It can be easy to accidentally
//let execution continue after calling a callback, when you really expected it to end.
//In order to make this easy to spot, and make sure execution stops in the way you expect,
//I recommend returning the callback function call.
// wrong!
function writeCsvFile(target, data, callback) {
convertToCsv(data, function (err, csv) {
if (err) {
callback(err); // oops! no return
}
// this line gets called even when theres an error
writeFile(target, csv, callback);
});
}
// right
function writeCsvFile(target, data, callback) {
convertToCsv(data, function (err, csv) {
if (err) {
return callback(err); // execution stops here
}
writeFile(target, csv, callback);
});
}
// Pattern
// If you're calling a synchronous function that might throw an exception,
// inside your asynchronous code, then calling your asynchronous
// code might also result in an exception.
// wrong!
function readJson(filename, callback) {
fs.readFile(filename, function (err, content) {
if (err) {
return callback(err);
}
// uh-oh! this line might throw an exception if the content
// is not valid JSON
var data = JSON.parse(content.toString());
return callback(null, data);
});
}
// right
function readJson(filename, callback) {
fs.readFile(filename, function (err, content) {
if (err) {
return callback(err);
}
try {
var data = JSON.parse(content.toString());
}
catch (e) {
return callback(e);
}
return callback(null, data);
});
}
// Pattern 2
// you can't use try-catch blocks around asynchronous code.
//Always, always, always pass errors back to the callback in asynchronous functions.
//As long as you're following the "Always check for errors in
//callbacks" rule the errors will be handled in the appropriate place.
// wrong!
function getRecord(id, callback) {
http.get('http://foo/' + id, function (err, doc) {
if (err) {
return callback(err);
}
if (doc.deleted) {
// this will not get caught by the function calling getRecord
throw new Error('Record has been deleted');
}
return callback(null, doc);
});
}
// right
function getRecord(id, callback) {
http.get('http://foo/' + id, function (err, doc) {
if (err) {
return callback(err);
}
if (doc.deleted) {
return callback(new Error('Record has been deleted'));
}
return callback(null, doc);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment