27

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
  • 669
  • 1
  • 6
  • 21
AnchovyLegend
  • 12,139
  • 38
  • 147
  • 231
  • 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 ? – adeneo Mar 16 '14 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 :) – AnchovyLegend Mar 16 '14 at 20:16
  • 1
    You are just invoking the function you have passed in particular condition, what is so confusion about this? – Suman Bogati Mar 16 '14 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? – AnchovyLegend Mar 16 '14 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. – keune Mar 16 '14 at 20:29
  • @Keune, I havent defined it in the above code block, nor elsewhere in my application. I thought it was defined by JavaScript, is it not? – AnchovyLegend Mar 16 '14 at 21:00
  • @AnchovyLegend It is defined by whatever library you're using, it looks like. There is _nothing_ special about callbacks - they are not defined "by JavaScript". They are normal functions, defined just like any other function. – Aaron Dufour Mar 16 '14 at 21:06

9 Answers9

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.

Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
  • 2
    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. – Meet Zaveri Feb 17 '18 at 08:40
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!

guy mograbi
  • 27,391
  • 16
  • 83
  • 122
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); });
liron_hazan
  • 1,396
  • 2
  • 19
  • 27
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
  • 18,210
  • 6
  • 124
  • 133
RAJA
  • 144
  • 4
1

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,525
  • 4
  • 24
  • 41
  • But isn't it still executed synchronously? So callback is basically passing function reference and it is still executed synchronously. Am I right? – Nithin B Apr 26 '19 at 06:24
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
  • 6,576
  • 7
  • 27
  • 48
Avinash Khadsan
  • 441
  • 3
  • 6
0

A callback is any function that is called by another function using parameter

Here a query for you Suppose that Consider how programmers normally write to a file:

- `fileObject = open(file)` //now that we have to wait for the file to open, after that we can write to this file*



 - fileObject.write("We are writing to the file.") // but i want to write , not wait

This case - where callbacks are helpful:

//we can pass **writeToFile()** (a callback function) to the open file function

 - fileObject = open(file, writeToFile)

//execution continues flowing -- we do not wait for the file to be opened

//once the file is opened we can write to it, but while we wait we can do other things

Zeeshan Adil
  • 1,937
  • 5
  • 23
  • 42
Avinash Maurya
  • 332
  • 3
  • 4
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

vaibhav gera
  • 101
  • 2
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);
jfk
  • 4,335
  • 34
  • 27