Reputation: 91
I am trying to understand webRTC flow by writing a simple local rtc communication. I am also trying to write the code using the async/await syntax, I tried using Promises and its working perfectly. I have the following script tag in my index.html
file
<script async src="test.js" onload="init()"> </script>
and my javascript code
const a = new RTCPeerConnection();
const b = new RTCPeerConnection();
async function init() {
try {
a.onicecandidate = e => {
console.log("alice candidate ", e);
if (e.candidate) {
b.addIceCandidate(e.candidate);
}
}
b.onicecandidate = e => {
console.log("bob candidate", e);
if (e.candidate) {
a.addIceCandidate(e.candidate);
}
}
let stream = await navigator.mediaDevices.getDisplayMedia({
video: { width: 800, height: 600 }
})
document.getElementById("local").srcObject = stream;
for (const track of stream.getTracks()) {
a.addTrack(track, stream);
}
let offer = await a.createOffer();
await a.setLocalDescription(offer);
await b.setRemoteDescription(a.localDescription);
let answer = await b.createAnswer();
await b.setLocalDescription(answer);
await a.setRemoteDescription(b.localDescription);
//my misunderstanding is here
b.ontrack = async e => {
console.log("test on track");
document.getElementById("remote").srcObject = e.streams[0];
}
} catch (err) {
console.err(err);
}
}
My problem comes when I try to put the ontrack event inside the async function. The ontrack event is never fired.
//when I put this event outside the async function the code works but not inside
b.ontrack = async e => {
console.log("test on track");
document.getElementById("remote").srcObject = e.streams[0];
}
I don't know if it is bad practice but I prefer the async/await syntax rather than the .then
. However as far as I know I can not write async/await outside an async function. So my question is why does then ontrack event do not fire inside the async init()
function but it does work when I put it outside in the top level scope.
Thank you.
Upvotes: 1
Views: 709
Reputation: 17330
ontrack fires as part of setRemoteDescription. However, in your async code you are only adding a ontrack handler later so it won't get triggered.
Upvotes: 2