Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

callback() or return callback()

It's possible I don't understand Node's event loop well enough.

Say I have a function foo which contains an asynchronous function async_func. Do I have

//1 function foo(callback) {        //stuff here        async_func(function() {             //do something             callback();        }); //this eventually get executed } 

or

//2 function foo(callback) {        //stuff here        async_func(function() {             //do something             return callback();        }); //never executed } 
like image 255
Colin Avatar asked Aug 13 '13 19:08

Colin


People also ask

Is callback and return same?

Return statements are used to indicates the end of a given function's execution whereas callbacks are used to indicate the desired end of a given function's execution.

Can we return in callback function?

A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value. Yes, it makes fun sense to try and return a value from a promise callback.

What is callback () in JavaScript?

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.

Why callback is called callback?

A Callback is a function that is to be executed after another function has finished executing — hence the name 'call back'.


1 Answers

Actually, in your sample 2, //never executed will be execute every time. It's returning from the callback, not from the wrapping function.

Sometimes the caller actually expects some return value and the behavior can change based on that. Another common reason to see a return callback() is just a clear way of short circuiting the function you're in. For example.

function doSomething(callback) {     something(function(err, data) {         if(err) return callback(err);         // Only run if no error     });     // Always run } 

Even though the return value isn't being used, it's using return to ensure that execution doesn't continue past the error conditional. You could just as easily write it this way which has the same effect.

function doSomething(callback) {     something(function(err, data) {         if(err) {             callback(err);             return;         }         // Only run if no error      });     // Always run } 
like image 140
Timothy Strimple Avatar answered Oct 25 '22 17:10

Timothy Strimple