Skip to content

Commit 8ce90c9

Browse files
committed
Wait for WebSocket state before send data
Closes: #169 PR-URL: #173
1 parent 0bf312e commit 8ce90c9

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

static/metacom.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ export class Metacom {
44
this.api = {};
55
this.callId = 0;
66
this.calls = new Map();
7-
this.socket.onmessage = ({ data }) => {
7+
this.socket.addEventListener('message', ({ data }) => {
88
try {
99
const packet = JSON.parse(data);
1010
const { callback, event } = packet;
@@ -23,7 +23,14 @@ export class Metacom {
2323
} catch (err) {
2424
console.error(err);
2525
}
26-
};
26+
});
27+
}
28+
29+
ready() {
30+
return new Promise(resolve => {
31+
if (this.socket.readyState === WebSocket.OPEN) resolve();
32+
else this.socket.addEventListener('open', resolve);
33+
});
2734
}
2835

2936
async load(...methods) {
@@ -48,8 +55,9 @@ export class Metacom {
4855
}
4956

5057
socketCall(methodName) {
51-
return (args = {}) => {
58+
return async (args = {}) => {
5259
const callId = ++this.callId;
60+
await this.ready();
5361
return new Promise((resolve, reject) => {
5462
this.calls.set(callId, [resolve, reject]);
5563
const packet = { call: callId, [methodName]: args };

0 commit comments

Comments
 (0)