From 7a3ab96d94073b22853992b5e0b3f8e26b8cfd51 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Thu, 9 Feb 2017 13:17:35 -0800 Subject: [PATCH] Fix race condition during initialization Summary: I discovered this while trying to pinpoint why Nuclide Inspector integration with RN is so flaky. It turns out that, for some reason, if I create a `WebSocket` instance early enough (which I need to when setting up DevTools integration), and the connection is fast enough (which it is on localhost), the `websocketOpen` message may arrive earlier than an `onopen` event handler is registered, causing the `onopen` handler to never fire. ``` mkdir ~/my-server cd ~/my-server npm i ws nano index.js ``` Paste this code: ```js const ws = require('ws'); const wss = new ws.Server({ port: 8099 }); ``` Run the server: ```js node index.js ``` Now, inside React Native, paste right after [these lines](https://github.com/facebook/react-native/blob/57010d63b6fbe8a986cd6fe560bfd83551a4562f/Libraries/Core/InitializeCore.js#L193-L194): ```js const ws = new window.WebSocket('ws://localhost:8099'); ws.onopen = function() { alert('open!'); }; ``` Closes https://github.com/facebook/react-native/pull/12305 Differential Revision: D4536554 Pulled By: gaearon fbshipit-source-id: 3021fa26b3bf275cba3704a7f3a30c77db69a1f8 --- Libraries/WebSocket/WebSocket.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Libraries/WebSocket/WebSocket.js b/Libraries/WebSocket/WebSocket.js index 551859e2e..12c6e4ad6 100644 --- a/Libraries/WebSocket/WebSocket.js +++ b/Libraries/WebSocket/WebSocket.js @@ -83,8 +83,8 @@ class WebSocket extends EventTarget(...WEBSOCKET_EVENTS) { this._eventEmitter = new NativeEventEmitter(RCTWebSocketModule); this._socketId = nextWebSocketId++; - RCTWebSocketModule.connect(url, protocols, options, this._socketId); this._registerEvents(); + RCTWebSocketModule.connect(url, protocols, options, this._socketId); } close(code?: number, reason?: string): void {