28

I am having a hard time understanding how the callback() function is used in the following code block.

How are we using callback() as a function, in the function body, when function callback() has not been defined?

What are the repercussions of passing true / false as parameters into the callback function below?

I appreciate any clarification, thanks in advance!

socket.on('new user', function(data, callback){
 if (nicknames.indexOf(data) != -1){
 callback(false);
 } else{
 callback(true);
 socket.nickname = data;
 nicknames.push(socket.nickname);
 updateUserList();
 }
});
David Thery
7291 gold badge7 silver badges23 bronze badges
asked Mar 16, 2014 at 20:11
7
  • 1
    The callback is an argument of the callback function for the on() function, so it's declared in what ever software you're using, I'm guessing socket.io, but I've never seen a callback like that in socket.io, are you sure there even is a callback function in whatever you're using ? Commented Mar 16, 2014 at 20:14
  • Thanks for the reply. I am using Node, JQuery, Javascript, -- yes, theres a callback function. Whats important to note is that callback function is passed into the function and then used in the function, which is what is confusing to me :) Commented Mar 16, 2014 at 20:16
  • 1
    You are just invoking the function you have passed in particular condition, what is so confusion about this? Commented Mar 16, 2014 at 20:20
  • 1
    Everything makes sense to me, except the callback(true) and callback(false) lines. I understand callback() is defined by JavaScript and functions are objects in JS so they can be passed as parameters into functions, etc. I don't understand the use in this instance, how might this help solve the problem at hand? I understand callback() is just a normal function that I'm invoking, but what does callback() actually do? Commented Mar 16, 2014 at 20:22
  • what does callback() actually do? it does whatever you want it to do, you define it. if you pass alert as callback it will either alert true or false, for example. Commented Mar 16, 2014 at 20:29

8 Answers 8

35

When you pass a function as an argument, it is known as a callback function, and when you return a value through this callback function, the value is a parameter of the passed function.

function myFunction(val, callback){
 if(val == 1){
 callback(true);
 }else{
 callback(false);
 }
}
myFunction(0, 
//the true or false are passed from callback() 
//is getting here as bool
// the anonymous function below defines the functionality of the callback
function (bool){
 if(bool){
 alert("do stuff for when value is true");
 }else {
 //this condition is satisfied as 0 passed
 alert("do stuff for when value is false");
 }
});

Basically, callbacks() are used for asynchronous concepts. It is invoked on a particular event.

myFunction is also callback function. For example, it occurs on a click event.

document.body.addEventListener('click', myFunction);

It means, first assign the action to other function, and don't think about this. The action will be performed when the condition is met.

answered Mar 16, 2014 at 20:28
Sign up to request clarification or add additional context in comments.

1 Comment

Best example(code snippet) I have encountered! I was so confused and then scraping lot of articles and and now this example provides crystal clear explanation.
5

I agree with you, the code in the snippet is very unclear.

The answers you got are great, however none refers to the actual use of callback in your code, and I would like to reference that specifically.

First, I will answer your question, and then I will elaborate on the complexity of it.

The answer

turns out socket.io are doing something very cool which is not the standard I know.. socket.io are passing the callback from the front-end to the backend!

So to answer your question what is this callback function - you have to look at your frontend code.

Look for code that looks like this

 socket.emit('new user', data, function( booleanParameter ){
 // what are you doing with booleanParameter here?
 });

I assume that in your case true/false values are meant to pass back to the frontend if new user was added (true) or not (false)..

Or perhaps if the nickname is already in use or not so that the frontend can show an error string if it is..

Basically, @SumanBogati was right in his answer, but I felt it was lacking the step of finding the callback in the front-end due to socket.io's special treatment.

Further Suggestion To make your code clearer

  • Change name of parameter data to nickname
  • Add comments - why are you placing nickname on socket?
  • add documentation

Use jsdocs to explain what the callback is doing

/**
 @callback NewUserCallback 
 @param {boolean} booleanParameter does something.. 
**/

and then on the function itself

/**
 @parameter {string} nickname 
 @parameter {NewUserCallback} callback
**/

The complexity

Usually, in nodejs, a callback expects the first argument to be an error, so reading your code, it says

socket.on('new user', function(data, callback){
 if (nicknames.indexOf(data) != -1){
 ///// THERE IS NO ERROR
 callback(false);
 }else{
 ///// THERE IS AN ERROR
 callback(true);
 /// do more stuff after the error
 socket.nickname = data;
 nicknames.push(socket.nickname);
 updateUserList();
 }
});

Not the pattern you'd expect, is it? I guess this is why you asked the question.

Still the question remains what socket.io's callback means, right? Perhaps their callback does not expect an error as first argument.

I have never used socket.io, and I was unable to find a documentation to clarify this. So I had to download their chat example and debug it ==> and so the answer I gave, they are passing the function from the frontend to the backend.

Socket.io should definitely stress this point in large font in their documentation under a title named "How does socket.io handle callbacks?" or "How does our callbacks work?".

Great question! Learned a lot from it!

answered Dec 23, 2014 at 10:28

Comments

2

I'll try to simplify with a "concrete" example (I hope).

Let's say I have a function that "calculates" the current day and I'll call that function each time I would need the current day ("Don't call us, we'll call you" or whatever).

var getCurrentDay = function (callback) {
 var currDate = new Date(); 
 callback(currDate, 'err');
 });
};
getCurrentDay(function (returnDay) { 
 logger.info('Today is: ' + returnDay); });
answered Dec 22, 2014 at 18:04

Comments

2

Without thinking too much, see the following example. In the following example, I just call the print function from the add function.

function print( ans ){
 console.log(ans) ; // 7
}
function add(a, b){
 print(a+b) ;
}
add(2,5);

What if I use the print function as a parameter? Without using print function from global scope I just pass the print function as an argument.

function print( ans ){
 console.log(ans) ; // 7
}
function add(a, b, callback){ // here callback = print
 callback(a+b) ;
}
add(2,5,print); // print function as a parameter 

Generally, JavaScript allows function as a parameter.

So any function that is passed as an argument is called a callback function. I think now callback is understandable to you.

gehbiszumeis
3,7595 gold badges28 silver badges45 bronze badges
answered Feb 21, 2019 at 6:41

1 Comment

But isn't it still executed synchronously? So callback is basically passing function reference and it is still executed synchronously. Am I right?
1

A callback function, is a function that is passed to another function (let’s call this other function "otherFunction") as a parameter, and the callback function is called (or executed) inside the otherFunction.

Here is my simple example for callback function

// callback add
function add(a, b){
 console.log(a+b);
}
// Main function
function getInput(cb) {
 c = 5+5;
 d = 6+6;
 if (typeof cb === 'function') {
 cb(c, d);
 }
}
getInput(add)

For detailed explanation refer the this link

KARTHIKEYAN.A
20.5k11 gold badges139 silver badges151 bronze badges
answered Jan 19, 2018 at 4:01

Comments

1

Callback function mean call after another:)

doHomeWork('math',alertMsg);

Above line said 1. call doHomeWork and then call 2. alertMsg, that's it.:)

function doHomeWork(subject,callback){
 console.info("study: "+subject);
 callback();
}
alertMsg = function(){
 console.info("alert");
}
doHomeWork('math',alertMsg);

Output:

study: math
alert
Vaibhav Vishal
7,2487 gold badges32 silver badges51 bronze badges
answered Jul 29, 2019 at 13:24

Comments

0

Function inside a function is called a callback function. Or let me say that the inside function which is present inside the parent function is called the callback function.

If you want to complete a task2 after task1. Then you can make task2 as the callback and this will run asyncronously

answered Jan 14, 2020 at 7:35

Comments

0

Here is one example where the usage of callback function is easy to understand.

  • A login function which performs user login with the server asynchronously.
  • Due to asynchronous call , we need to get the result of login once the date receives from the server.

 const axios = require('axios');
 function login(loginData,callbackSuccess,callBackFailure) {
 axios
 .post("/api/login",loginData)
 .then((response) => {
 callbackSuccess(response);
 })
 .catch((error) => {
 callBackFailure(error);
 });
 }
 
 function callbackSuccess(data) {
 console.log("Login response :",data);
 }
 
 function callBackFailure(error) {
 console.log("Login failed :",error);
 }
 
 let userData = {
 username : "test",
 password : "abcd123"
 }
 
 login(userData,callbackSuccess,callBackFailure);

answered Oct 3, 2020 at 21:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.