Given the example below, if I wanted to await player.play(), do I have to add async in TWO places since foo will ultimately be the executed function?
example:
const foo = (player) => {
let foo = videojs;
foo.addEventListener('ready', () => {
player.play()
}
}
would it be:
const foo = async (player) => {
let foo = videojs;
foo.addEventListener('ready', async () => {
await player.play()
}
}
await foo();
or:
const foo = (player) => {
let foo = videojs;
foo.addEventListener('ready', async () => {
await player.play()
}
}
foo();
If you want foo to return a promise that resolves when the .play()-returned promise resolves, then you could promisify addEventListener.
Something like this:
const whenEvent = (elem, event) => new Promise((resolve) =>
elem.addEventListener(event, resolve, { once: true })
);
const foo = async (player) => {
await whenEvent(videojs, 'ready');
await player.play();
};
foo().then(() => console.log("foo resolved"));
Note that a promise can only resolve once, while an event listener can be called multiple times. So this promisified version (whenEvent) will only capture the first event, and then stop listening. whenEvent (and thus foo) should be called again to deal with a next occurrence of the event.