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](57010d63b6/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
This commit is contained in:
Dan Abramov 2017-02-09 13:17:35 -08:00 committed by Facebook Github Bot
parent a9ccc8133e
commit 7a3ab96d94

View File

@ -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 {