diff --git a/src/client.ts b/src/client.ts index 39acfb15..6f3b60d3 100644 --- a/src/client.ts +++ b/src/client.ts @@ -107,21 +107,24 @@ export default class Client { } }; - this.transports[Role.sub].pc.ondatachannel = (ev: RTCDataChannelEvent) => { - if (ev.channel.label === API_CHANNEL) { - this.transports![Role.sub].api = ev.channel; - ev.channel.onmessage = (e) => { - if (this.onspeaker) { - this.onspeaker(JSON.parse(e.data)); - } - }; - return; - } + const apiReady = new Promise((resolve) => { + this.transports![Role.sub].pc.ondatachannel = (ev: RTCDataChannelEvent) => { + if (ev.channel.label === API_CHANNEL) { + this.transports![Role.sub].api = ev.channel; + ev.channel.onmessage = (e) => { + if (this.onspeaker) { + this.onspeaker(JSON.parse(e.data)); + } + }; + resolve(); + return; + } - if (this.ondatachannel) { - this.ondatachannel(ev); - } - }; + if (this.ondatachannel) { + this.ondatachannel(ev); + } + }; + }); const offer = await this.transports[Role.pub].pc.createOffer(); await this.transports[Role.pub].pc.setLocalDescription(offer); @@ -130,6 +133,8 @@ export default class Client { await this.transports[Role.pub].pc.setRemoteDescription(answer); this.transports[Role.pub].candidates.forEach((c) => this.transports![Role.pub].pc.addIceCandidate(c)); this.transports[Role.pub].pc.onnegotiationneeded = this.onNegotiationNeeded.bind(this); + + return apiReady; } leave() {