0

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.

4
  • 1
    this code is fine as it is. Commented May 29, 2013 at 3:28
  • 1
    This question is better suited for codereview.stackexchange.com but why not get rid of the if (doc) {... and just do callback(doc)? Does your callback look at arguments.length? If so, then you could do callback.apply(null, [].slice.call(arguments, 1)) if you really want. Commented May 29, 2013 at 3:31
  • I guess my issue is this - my callback call in reality contains more code - while I know this works I know that there is a way to wrap this entire inner part inside of another function and return from that. But just can't remember how Commented May 29, 2013 at 3:32
  • why can't you write another wrapper method called callCallback where you put all the code related to calling the callback and then call that method from all the three places with necessary parameters Commented May 29, 2013 at 3:35

2 Answers 2

1

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.