1

There are a client and server side code:

Client:

socket.on('connect',  function() {
        showSystemMessage('Connected.');

        socket.emit('setuser', wm, function(data){
            console.log(data);
            socket.emit('whoisonline', wm, function(data){
                getOnlineFriends(data);
            });
        });
    });

Server:

io.on('connection', function(socket) {
        socket.on('setuser', function (data, cb) {
            cb(data);
        });
});

I get error:

TypeError: undefined is not a function on line 18

Line 18:

socket.on('setuser', function (data, cb) {
     cb(data); // Line 18
});

Then i tried your solution, I got:

TypeError: undefined is not a function in line 35

socket.on('whoisonline', function (data, cb) {
            redis.sinter('user.friend:' + data.id, 'onlineusers', function(error, intersection) {

                friends.online = intersection;
                friends.total  = intersection.length;

                if(friends.total > 0){
                    intersection.forEach(function(entry) {
                        var socketid = clients[entry];
                        io.sockets.connected[socketid].emit('in', { id : data.id, total : friends.total });
                    });
                }

                cb(friends); // Line 35
            });
        });

2 Answers 2

4

In my case the following works:

  • at the server side

    socket.on('setuser', (name, cb) => { cb(name); });
    
  • at the client side

    socket.emit('setuser', 'user data', r => { console.log(r); });
    
Sign up to request clarification or add additional context in comments.

Comments

0

Socket.io doesn't work with callbacks, you have to work with .emit() and .on(). In this case your source code would look like:

Client:

socket.on('connect',  function() {
        showSystemMessage('Connected.');

        socket.emit('setuser', wm);
        socket.on("setuser", function(data){
            console.log(data);
            socket.emit('whoisonline', wm);
            socket.on("whoisonline", function(data) { 
                getOnlineFriends(data);
            });
        });
    });

Server:

io.on('connection', function(socket) {
        socket.on('setuser', function (data) {
            socket.emit("setuser", data);
        });
});

4 Comments

Hm, thank you, seems work, but I get callback againn after rewrite on your code. Edited question
@AhmedFaud Replace line 35 with socket.emit("whoisonline", friends);
We use socket.io with callbacks all the time. It works fine.
@JeremyTM hmm you seem to be right, I must've missed that 5 years ago.

Your Answer

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.