Search code examples
javascriptasync-awaitwebrtc

How to await candidates in WebRTC?


Is there any easy way to await the full completed with candidates ? We can await the offer & description, but I dont see a way to await the candidates (full sdp to be sent to the signalling server).

E.g.:

const pc = new RTCPeerConnection(configuration);
const sendChannel = pc.createDataChannel("sendChannel");
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);

// need something like this;
await pc.onIceCandidateComplete();; 

// send the offer to signaling server once we have all the data.
send(offer);

I see there oniceconnectionstatechange(), and onicecandidate() that can be used, but none support await async, or I can't find a good example.

Has anyone come up with a good solution for this or is there some reason to not have this functionality? What's the best way?


Solution

  • There is no directly awaitable event. You can use a construct like the waitUntilEvent function found here:

    await (new Promise(r => {
      pc.addEventListener(
        'icegatheringstatechange',
        () => pc.gatheringState === 'complete' && r()
     )
    }));
    

    Note however that this state change can take a lot of time (30s+) in certain cases. This bug has some notes. Typically you'll want to wait for other conditions like the first relay candidate or add a timeout.