Failed to execute 'send' on 'WebSocket'
<p>I'm new to javascript and wish to use websockets. When I created a Websocket object and tried to send on it, I was getting the following error:</p>

<pre><code>InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
</code></pre>

<p>So I have solved this using the closure below. Is this a reasonable approach to solving my problem? Is there a better approach? One issue with my approach would be if someone later were to reassign the value of <code>ws.onopen</code>. I'm using redux so I will want to use my send when dispatching requests to the backend. I am also using ES6, webpack and node.js.</p>

<pre><code>const ws = new WebSocket("ws://echo.websocket.org/");
ws.onmessage = msg =&gt; console.log(msg);

const send = (()=&gt;{

    const queue = [];
    ws.onopen = () =&gt; queue.forEach(msg =&gt; ws.send(msg));

    return (msg) =&gt; {
        if(ws.readyState === ws.OPEN){
            ws.send(msg);
        }
        else{
            queue.push(msg);
        }
    };

})();

send("foo");
send("bar");
</code></pre>