From ec76383a1a85e02aca44954b48c719a69e291e90 Mon Sep 17 00:00:00 2001 From: Andrew Lavers Date: Sat, 4 Apr 2020 11:02:21 -0400 Subject: [PATCH] Handle connection after connect event was emitted It's possible for connect promise to resolve after the resolved connection has already been established, which means we miss the connect event. This can happen when Bluebird is set as the global Promise, and we connect to an ip address host for example. This fix checks to see if that's the case and invokes the connection handler directly. Thanks @luin for the recommendation. Fixes #977 --- lib/redis/index.ts | 6 +++++- test/functional/connection.ts | 9 +++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/redis/index.ts b/lib/redis/index.ts index 1cf12325..eb8382df 100644 --- a/lib/redis/index.ts +++ b/lib/redis/index.ts @@ -304,7 +304,11 @@ Redis.prototype.connect = function (callback) { stream.setKeepAlive(true, options.keepAlive); } - stream.once(CONNECT_EVENT, eventHandler.connectHandler(_this)); + if (stream.connecting) { + stream.once(CONNECT_EVENT, eventHandler.connectHandler(_this)); + } else { + process.nextTick(eventHandler.connectHandler(_this)); + } stream.once("error", eventHandler.errorHandler(_this)); stream.once("close", eventHandler.closeHandler(_this)); diff --git a/test/functional/connection.ts b/test/functional/connection.ts index c8edf79f..59b9a6cf 100644 --- a/test/functional/connection.ts +++ b/test/functional/connection.ts @@ -4,6 +4,7 @@ import * as sinon from "sinon"; import { expect } from "chai"; import MockServer from "../helpers/mock_server"; import * as Bluebird from "bluebird"; +import { StandaloneConnector } from "../../lib/connectors"; describe("connection", function () { it('should emit "connect" when connected', function (done) { @@ -423,5 +424,13 @@ describe("connection", function () { done(); }); }); + + it("works when connection established before promise is resolved", (done) => { + const socket = new net.Socket(); + sinon.stub(StandaloneConnector.prototype, "connect").resolves(socket); + socket.connect(6379, "127.0.0.1").on("connect", () => { + new Redis().on("connect", () => done()); + }); + }); }); });