回调(false)和回调(true)有什么作用

What does callback(false) and callback(true) do?

本文关键字:回调 什么 作用 false true      更新时间:2023-09-26

我正在研究一个nodejs聊天的示例项目,我真的无法理解当callback(false)callback(true)在这里被调用时会发生什么......

io.sockets.on('connection', function(socket){
    socket.on('new user', function(data, callback){
        if(usernames.indexOf(data) != -1){
            callback(false);
        } else {
            callback(true);
            socket.username = data;
            usernames.push(socket.username);
            updateUsernames();
        }
    });

调是确认函数

服务器

        socket.on('new user', 
          function(data, calback){
                  // incidentally(not needed in this case) send back data value true 
                  calback(true);
          }
         );

客户

    socket.emit('new user', 
              data, 
              function(confirmation){
                       console.log(confirmation);
                      //value of confirmation == true if you call callback(true)
                      //value of confirmation == false if you call callback(false) 
              }
             );

socket.on 侦听事件 'new_user'此事件通过以下方式触发:

    var data= "mydata"
    var callback=function(bool){
      if(bool){
        console.log('success')
      }else{
        console.log('error')
      }
    }
socket.trigger('new_user',[data,callback])

回调只是作为触发器参数的函数传递