Lets take a look at the following code:
mongodb.js
var mongo = require('mongodb')
, mongodb = module.exports;
mongodb.database = function(key, dbName, dbServer, callback){
var db = new mongo.Db(dbName, dbServer);
db.open(function(error, connection){ // 5
if(error){ // 1
throw error;
}
return callback(null, connection);
});
};
mongodb.collection = function(dbKey, collName, callback){
mongodb.database(dbKey, function(error, connection){
connection.collection(collName, function(error, collection){ // 2
if(error){ // 3
throw error;
}
return callback(null, collection);
});
});
}
model.js
var db = require('./mongodb.js');
var model = module.exports;
model.test = function(callback){
db.collection('users', function(error, collection){ // 4
// do something.
});
}
My question is, why do we always do "error, resource" when a callback is passed through, because, take a look at 1
We are dealing with the error, so it can't even reach 2*
Same with 3 and 4 they will always be NULL, because the error is handled on a different layer. Now why wouldn't I just do this at 5:
db.open(function(error, connection){
if(error){ // 1
return errorHandler(error);
}
return callback(collection);
});
the errorHandler function would be a function that deals with major errors, so we don't have to use them at each layer, same story for for example mongodb.findOne, why do we have to deal with errors when we pass in the callback?