diff --git a/src/Client.tsx b/src/Client.tsx index be24ec0..6dd8627 100644 --- a/src/Client.tsx +++ b/src/Client.tsx @@ -81,6 +81,14 @@ export class Client { } private handleNewData(parsed: any) { + if (parsed.requestId) { + const callback = this.requestCallbacks[parsed.requestId]; + if (callback) { + callback(parsed); + delete this.requestCallbacks[parsed.requestId]; + } + return; + } for (const key in parsed) { if (Object.prototype.hasOwnProperty.call(parsed, key)) { const val = parsed[key]; @@ -105,6 +113,17 @@ export class Client { this.send(JSON.stringify(jsonObj)); } + lastRequestId = 0; + requestCallbacks: Record void> = {}; + + request(obj: object) { + const id = ++this.lastRequestId; + this.sendJson({requestId: id, ...obj}); + return new Promise((resolve) => { + this.requestCallbacks[id] = resolve; + }); + } + close() { this.reconnectTimer.tryCancel(); if (this.closed) return;