Created
January 17, 2012 20:31
-
-
Save polotek/1628712 to your computer and use it in GitHub Desktop.
Some node gotchas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.somethingAsync = function(callback) { | |
setTimeout(function() { | |
callback(null "done"); | |
}, 100); | |
} | |
exports.failingAsync = function(callback) { | |
setTimeout(function() { | |
callback(new Error("failed")); | |
}, 100); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var lib = require('a_module'); | |
function getData(id, someParam, callback) { | |
var data = {} | |
lib.failingAsync(function(err, result) { | |
// you should be returning here | |
if(err) { return callback(err); } | |
// no way to catch this because we're in a new stack | |
if(!someParam) { throw new Error('Missing someParam'); } | |
// do something with result | |
data.result = result; | |
// if there is was an error, this got called twice. | |
callback(null, data)); | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var lib = require('a_module'); | |
var myRegex = /some regex/; | |
function getData(callback) { | |
var data = {} | |
lib.somethingAsync(function(err, result) { | |
// you should be returning here | |
if(err) { return callback(err); } | |
// do something non-trivial with result | |
if(result.test(myRegex)) { | |
data.result = result + " for getData"; | |
return callback(null, data); | |
} else if(result == "stop now") { | |
// don't continue | |
return; // where's your callback in this case? | |
} else { | |
// return empty data | |
return callback(null, data); | |
} | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var lib = require('a_module'); | |
function getData(callback) { | |
var data = {} | |
lib.failingAsync(function(err, result) { | |
// you should be returning here | |
if(err) { callback(err); } | |
// do something with result | |
data.result = result; | |
// if there is was an error, this got called twice. | |
callback(null, data)); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment