0

I can't find the right term relating to this thing, so I decided to write a question.

I have this function:

var methods = {

    login: function(callback){

        $someCustomService
            .login() // This returns $http
            .success(function(data){

                // callback(true, data); --- doing this without using 'return' also works
                return callback(true, data);
            })
            .error(function(data){

                return callback(false, data);

            })

    }

};  

Call the function:

$anotherCustomService.login(function(success, data){

    if(success){
        alert('Success');
    }else{
        alert('Fail');
    }

    console.log(data);

});

The line return callback(true, data); works just fine, but if I changed it to callback(true, data); without using return it also works. Now I'm confused whether what to use.

EDIT

BTW, the main reason I ask this, is because of this:
angular.noop

function foo(callback) {
  var result = calculateResult();
  (callback || angular.noop)(result);
}  

It didn't use any return which I learned first in coding javascript functions.

fiberOptics
  • 6,955
  • 25
  • 70
  • 105
  • What don't you understand? Are you asking what `return` means? – SLaks Sep 23 '14 at 15:14
  • Do you have the code for `$someCustomService`? If so, does it have any interest in the return value of the callbacks when it invokes them? It's not so much a matter of style as it is a matter of API semantics. –  Sep 23 '14 at 15:20

1 Answers1

1

Callback functions typically return nothing, they're of type void so to say. Neither the success and error methods care what the callbacks return, nor do you. Whether you pass the result through does not make any difference, it's undefined anyway in your case.

Therefore, use the shorter solution without any return.

Sometimes you still will see callbacks that use return, but only for helping with control flow. Assuming an error case doesn't pass data, you might for example write

$anotherCustomService.login(function(success, data){
    if(!success)
        return alert('Fail');
//      ^^^^^^
    alert('Success');
    console.log(data);
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • The link is so helpful. I was thinking if there is any effect on memory management when using or not using `return`. – fiberOptics Sep 23 '14 at 15:53