Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SocketIO emit with callback fails while upgrading 0.9.16 to 1.3.5

In 0.9.16, I use socket.emit with callback so that the chat server return some data and I can handle the result as per the acknowledgement. But after the upgrade to 1.3.5 I've found a error in console like this

Uncaught TypeError: Cannot read property 'apply' of undefined.

I've done something like this,

From web

socket.emit('userToUser', { 'usename': 'John',
'message': 'hi'
}, function(callback){
//callback handled
});

Chat Server

socket.on('userToUser', function(content, callback){
//do something
if(callback) return callback({'result':'success', 'messageid':content.messageid, 'chatid':content.chatid});
});

When I removed the callback from client side, there is no error. So I believe there will be some changes to be done in the callback.

I'm getting the acknowledgement and the chat is working properly, but my concern is about the console error which leads to socketio.js

Socket.prototype.onack = function(packet){
  debug('calling ack %s with %j', packet.id, packet.data);
  var fn = this.acks[packet.id];
  fn.apply(this, packet.data);
  delete this.acks[packet.id];
};

Guys, please help

like image 265
Tony Jose Avatar asked Apr 29 '15 06:04

Tony Jose


People also ask

What does Socketio emit do?

emit() to send a message to all the connected clients. This code will notify when a user connects to the server.

How do I emit to all users socket IO?

To broadcast an event to all the clients, we can use the io. sockets. emit method. Note − This will emit the event to ALL the connected clients (event the socket that might have fired this event).

What port does Socketio use?

We make the http server listen on port 3000.

How do you handle socket IO errors?

Error handling​ There is currently no built-in error handling in the Socket.IO library, which means you must catch any error that could be thrown in a listener. On the server-side, using EventEmitter. captureRejections = true (experimental, see here) might be interesting too, depending on your use case.


1 Answers

Finally I've fixed the issue. It was a mistake in my code , I've done multiple callbacks in the chat server. like this:

socket.on('userToUser', function(content, callback){

  mysql.insertChat(content, function(err, data){
      return callback({'result':'1'})   //first callback
  })  
  sendToUser(content, function(errm successData){
      return callback({'result':'success','chatid':content.chatid});
      //second callback ->wrong
  })

});

In the previous versions it was a warning, now its an error !! That's it. So please avoid multiple callbacks

Please have a look at this and might be useful for every nodejs developer: http://www.toptal.com/nodejs/top-10-common-nodejs-developer-mistakes/#remote-developer-job

Thanks guys for upvoting !

like image 178
Tony Jose Avatar answered Sep 28 '22 10:09

Tony Jose