Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.emit() error handling with socket.io

I am using

$('btn').click(function() {
    socket.emit('load more', function (objs) {
        // do something
    });
});

on the client to get objects from the server.

But sometimes the connection is lost and nothing happens. How can I make error handling such that I can tell the user that the server doesn't answer instead of letting nothing happen as it is now?

Edit

So what I want is something like

$('btn').click(function() {
    var emit = socket.emit('load more', function (objs) {
        // do something
    });

    if (!emit) {
        console.log("It didn't work. Maybe you lost connection or the server is not running.");
    }
});

I do know that I cannot do this, but would it be possible using promises or something?

like image 532
Jamgreen Avatar asked Sep 10 '26 01:09

Jamgreen


1 Answers

Second argument to emit is the data that we need to pass on the event 'load more'.

If you just want to server to let know that you need data, without passing any extra info, just do socket.emit('load more'). In server, listen for event 'load more' and send data to client with particular event-name. In Client, listen for the event 'event-name' and receive data in callback like,

socket.on('event-name', function(data_from_server){
    //do something
});

If you want to handle the case, where server not sends any data then wait for some time after sending the event 'load mode' and handle it.

like image 93
RaR Avatar answered Sep 11 '26 14:09

RaR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!