Callback function example

2019-01-11 11:11发布

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{} hasn't been defined? What are the reprecussions of passing true / false as paramters 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();
    }
});

5条回答
Rolldiameter
2楼-- · 2019-01-11 11:19

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!

查看更多
太酷不给撩
3楼-- · 2019-01-11 11:20

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

查看更多
冷血范
4楼-- · 2019-01-11 11:24

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); });
查看更多
做自己的国王
5楼-- · 2019-01-11 11:26

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.

查看更多
别忘想泡老子
6楼-- · 2019-01-11 11:44

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);
  }
}

For detailed explanation refer the this link

查看更多
登录 后发表回答