From 991eb0b0289bbbf680099e6d42b302beee7568b8 Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Sun, 26 Jun 2022 09:08:19 +0200 Subject: [PATCH] fix: ensure buffered events are sent in order Before this commit, an event sent in the "connect" handler could be sent before the events that were buffered while disconnected. ```js socket.on("connect", () => { socket.emit("bar"); }); socket.emit("foo"); // buffered while disconnected ``` In the example above, the "bar" event was sent first, which is not correct. Related: https://github.com/socketio/socket.io-client/issues/1458 Backported from https://github.com/socketio/socket.io-client/commit/34f822f783c6985039c0733a96d1fab8f01b1edf --- lib/socket.js | 2 +- test/socket.js | 20 ++++++++++++++++++++ test/support/server.js | 4 ++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/socket.js b/lib/socket.js index a0e1d1320..ab6422694 100644 --- a/lib/socket.js +++ b/lib/socket.js @@ -332,8 +332,8 @@ Socket.prototype.onack = function (packet) { Socket.prototype.onconnect = function () { this.connected = true; this.disconnected = false; - this.emit('connect'); this.emitBuffered(); + this.emit('connect'); }; /** diff --git a/test/socket.js b/test/socket.js index 91abd9d81..691624ca5 100644 --- a/test/socket.js +++ b/test/socket.js @@ -176,4 +176,24 @@ describe('socket', function () { done(); }); }); + + it('should emit events in order', function (done) { + var socket = io('/', { autoConnect: false }); + var i = 0; + + socket.on('connect', function () { + socket.emit('echo', 'second', function () { + expect(++i).to.eql(2); + + socket.disconnect(); + done(); + }); + }); + + socket.emit('echo', 'first', function () { + expect(++i).to.eql(1); + }); + + socket.connect(); + }); }); diff --git a/test/support/server.js b/test/support/server.js index 23dd49f32..ca37cb643 100644 --- a/test/support/server.js +++ b/test/support/server.js @@ -40,6 +40,10 @@ server.on('connection', function (socket) { socket.emit('hi'); }); + socket.on('echo', function (arg, callback) { + callback(arg); + }); + // ack tests socket.on('ack', function () { socket.emit('ack', function (a, b) {