Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not just call a function from another function instead of using a callback?

Tags:

javascript

I'm a little confused, not about what callbacks are used for but because I see callbacks used in scenarios often where it seems like passing a function as an argument to another function isn't necessary because you can just invoke the function you want invoked after the code in the current function is finished executing. For example:

function hello( a , b ) {
    var result = a + b; 
    myFunction();
}

myFunction() {
    //code
}

hello(1,2);

What's confusing is, I've seen a lot of examples where a callback is being used in a scenario just as simple as the first code I wrote where it seems to me a callback isn't needed at all:

function hello(a, b, callback) {
    var result = a + b;
    callback();
}

myFunction() {
    //code
}

hello(1, 2, myFunction);

I used a callback there but I could've just called the function myFunction after the code executed without passing myFunction as an argument. I understand a framework or library doesn't know the name of the function you'll want called after code is finished executing so passing the function you want called later as an argument seems to make sense then but when you know the name of the function you want invoked after whatever code is executed in a function, why not just invoke it just as I did in the first example I gave? I would appreciate your help. Thanks

like image 922
codebmanj Avatar asked May 27 '16 00:05

codebmanj


1 Answers

Benefit 1

One of the reasons callbacks are nifty is that you can call your function with any callback at all:

hello(1, 2, myFunction1);
hello(1, 2, myFunction2);
...
hello(1, 2, anyFunctionAtAll);

Whithout the possibility of passing a callback as an argument, your hello would be tied to always execute myFunction, since it's fixed on your function code.

Benefit 2

The other reason is that with callbacks you prevent blocking on long-running operations. You pass a callback to run after the function operations are complete, and while it is processing it cedes control back to the main event loop instead of blocking.

For example, if you are about to execute these operations:

hello(1, 2, myCallback);
console.log('Im not waiting for hello!')

In case your myCallback function spends too much time processing, the console operation is not going to wait for it to terminate its execution.


If you want to understand more, an know any other javascript caveats, I recomend this and this


Conclusion

If you think you won't benefit of one of this things, so callbacks are not necessary on your scenario.

like image 108
inafalcao Avatar answered Sep 28 '22 13:09

inafalcao