Given this code:
var something = function(callback) {
if(condition) {
Mongoose.findOne(id, function(err, doc) {
if(doc) {
callback(doc);
} else {
callback();
}
});
} else {
callback();
}
}
How would I rewrite it in a cleaner way so that 'callback' is just called in one place. I assume I can wrap this entire thing somehow and do that - I've seen it but cannot get it quite right.
Since you said there are complex steps to call the callback, try the below
var something = function(callback) {
var callCallback = function(doc){
//do all other things you want to do to call the callback
callback(doc);
};
if(condition) {
Mongoose.findOne(id, function(err, doc) {
if(doc) {
callCallback(doc);
} else {
callCallback();
}
});
} else {
callCallback();
}
}
var something = function (callback) {
var f = function (e, d) { callback(d) };
if (condition) {
Mongoose.findOne(id, f);
} else {
f();
}
}
my reasoning is that if d is false then we still can pass it on to callback and it will be the same almost as passing no arguments at all.