Reputation: 1158
I have read many tutorials on how to write callbacks. However, none of these get really into what the recommended design is.
Imagine this piece of code which logs user in through imaginary DB with imaginary query function to keep it simple but still compilable and runnable:
var db = {};
// fake query function for demonstration purposes
db.query = function(query, cb) {
console.log('Running an expensive query:', query);
if (query == 'get uid from db')
return cb(null, {password: 'pwd'});
return cb(null, {password: 'pass'});
}
var login = function(user, password, cb) {
var q = 'get ' + user + ' from db';
db.query(q, function(err, user) {
if (err || !user || user.password != password)
return cb(false);
return cb(true);
});
};
console.log('pre');
login('uid', 'pwd', function(success) {
console.log('Login', success ? 'was successful' : 'failed');
});
console.log('post');
module.exports = null;
In this code, I am relying on the DB layer to handle the callback of query
function in a correct asynchronous way so that my own callback in login
function gets called asynchronously too.
However, is this correct design of my own callback? Shall I better wrap the callbacks in db.query
into a process.nextTick()
call?
Or is there even better way?
What I am interested in, is to get the understanding of how one shall design these two types of callbacks:
Upvotes: 2
Views: 953
Reputation: 5385
You should design all node callbacks according to the convention:
var callback = function(err, data1, data2){
}
The first argument to a callback should always be any error that might have occurred.
You should follow this convention regardless of whether it's a callback for a node standard library or your own code.
If you follow this convention then you'll be able to use libraries such as async.js or other promises libraries that rely on this convention. Domains rely on this convention as well.
Upvotes: 3