diff --git a/lib/client.js b/lib/client.js index 565bb8c..cc6f525 100644 --- a/lib/client.js +++ b/lib/client.js @@ -519,6 +519,8 @@ export default class Client extends EventTarget { } return new Promise((resolve, reject) => { + let removeEventListeners; + let handleMessage = (event) => { let msg = event.detail.message; @@ -531,18 +533,31 @@ export default class Client extends EventTarget { try { result = done(msg); } catch (err) { - this.removeEventListener("message", handleMessage); + removeEventListeners(); reject(err); } if (result) { - this.removeEventListener("message", handleMessage); + removeEventListeners(); resolve(result); } // TODO: handle end of labeled response somehow }; + let handleStatus = () => { + if (this.status === Client.Status.DISCONNECTED) { + removeEventListeners(); + reject(new Error("Connection closed")); + } + }; + + removeEventListeners = () => { + this.removeEventListener("message", handleMessage); + this.removeEventListener("status", handleStatus); + }; + this.addEventListener("message", handleMessage); + this.addEventListener("status", handleStatus); this.send(msg); }); }