1

I have the following code from Twilio to access local camera on browser :

async function ShowLocalVideo() {   
    Twilio.Video.createLocalVideoTrack().then(track => {
        const localMediaContainer = document.getElementById('LocalMedia');
        localMediaContainer.appendChild(track.attach());        
      });
}

I would like to make sure the user Granted Access to the camera before continuing the execution of other steps. Or at least he responded. So I'm calling

await ShowLocalVideo();
alert('Hi !');  

But alert Hi ! is trigerred before the browser says : This file wants to use your camera.

Is is possible to make sure the code doesn't continue until the user responds to This file wants to use your camera. ?

Thanks, Cheers

Thomas Carlton
  • 5,344
  • 10
  • 63
  • 126
  • You're awaiting ShowLocalVideo but there's another async call within that (the "then" callback) which you're not waiting for. https://stackoverflow.com/questions/55019621/using-async-await-and-then-together (and many others) – ADyson Sep 27 '21 at 16:03
  • where this code is executed `await ShowLocalVideo();`? – Alan Omar Sep 27 '21 at 16:04

1 Answers1

3

You're mixing async/await syntax with using Promise .then. Since you're not awaiting on the result of createLocalVideoTrack().then(...), the async function will return early. You can correct this by replacing .then with await the following way:

async function ShowLocalVideo() {   
    const track = await Twilio.Video.createLocalVideoTrack();
    const localMediaContainer = document.getElementById('LocalMedia');
    localMediaContainer.appendChild(track.attach());        
}

Alternatively, you can await on the result of createLocalVideoTrack().then(...), but that would mix the styles and create confusion.

m1el
  • 176
  • 5