Home > OS >  Returning localDescription from RTCPeerConnection
Returning localDescription from RTCPeerConnection

Time:07-24

When I try to return the localDescription from the code below, I get a response that does not contains candidate parameter under sdp, as shown in the screenshot.

Can anyone please help me understand what am I missing here?

Also, I am not using something like conn.onicecandidate = evt => {} on purpose because I directly want to return a value from the function below.

async function getLocalDesc() {
  const conn = new RTCPeerConnection();
  conn.createDataChannel('');
  const offer = await conn.createOffer();
  await conn.setLocalDescription(offer);
  return conn.localDescription;
}

(async () => {
  console.log(await getLocalDesc())
})();

enter image description here

CodePudding user response:

ICE Candidate gathering takes time and you just await setLocalDescription which starts the process. It does not wait for gathering to be complete or any candidates, you'll need to wait for either the candidate event or the gatheringstatechange event (to a gatheringState of completed) for the SDP to contain the candidates.

https://webrtchacks.com/trickle-ice/ has some details on why that is not a good idea though.

CodePudding user response:

We can return a promise from our function that will provide the required param i.e. candidate once it gets resolved.

async function getLocalDesc(){
    const conn = new RTCPeerConnection();
    conn.createDataChannel('');
    const offer =  await conn.createOffer();
    await conn.setLocalDescription(offer);
    return new Promise(resolve =>  conn.onicecandidate = event => resolve(event));
}

(async () => {
  console.log(await getLocalDesc())
})();

  • Related