let socket; function noPromise(){ let resolve, reject; let np = new Promise((ok, fail) => {resolve = ok; reject = fail}); np.resolve = resolve; np.reject = reject; return np } function asynchronize({s, chunkEventName, endEventName}){ return async function* (){ const chunks = {}; const promises = {}; const clear = i => (delete chunks[i], delete promises[i]) let chunkCount = 0; let promiseCount = 0; let end = false; if (!('on' in s)){ s.on = function(eventName, callback){ this['on' + eventName] = callback; } } s.on(chunkEventName, data => { chunks[chunkCount] = data if (chunkCount in promises){ promises[chunkCount].resolve(chunks[chunkCount]) clear(chunkCount) } chunkCount++ }) s.on(endEventName, () => { end = true; for (let i in promises){ promises[i].reject(new Error('End Of S')) } }) while (!end){ let p = noPromise() if (promiseCount in chunks){ p.resolve(chunks[promiseCount]) clear(promiseCount) } promises[promiseCount] = p; promiseCount++ yield p; } } } function msg2dom({nick, message, timestamp}){ const div = document.createElement('div') div.innerHTML = `${nick}:${message}` return div; } let RPC = { addMessage(data){ chat.appendChild(msg2dom(data)) }, getUserCount({value}){ chat.appendChild(msg2dom({nick: 'чатег', message: `${value} user online` , timestamp: (new Date()).getTime()})) } }; (async () => { while (true){ try{ socket = new WebSocket("ws://localhost:8999/"); let aGena = asynchronize({s: socket, chunkEventName: 'message', endEventName: 'close'}); for await (let msg of aGena()){ let data = JSON.parse(msg.data) if (data.func in RPC){ RPC[data.func](data) } } } catch (e){ console.log(e) } } })() send.onclick = function(){ if (socket && typeof socket.send === 'function') socket.send(JSON.stringify({func: 'addMessage', nick: nick.value, message: msg.value})) }