Skip to content Skip to sidebar Skip to footer

What Happens When New Listener Is Attached When An Event Is Pending?

Say I have a web worker _worker, and I attach a listener to it like so: _worker.addEventListener('message', (event) => { window['test'] = event.data||'foo' }); Let's say I

Solution 1:

As we are attaching the second listener, the worker has already fired a message event, and the event loop is waiting to fire the first listener

Yes, the second listener will be included in the list of listeners to be notified of the event here. If the event loop is still waiting to call the listeners, the event has not yet really occurred in the main process, even when the worker has already triggered it and it is waiting in the queue.

The edge case where you could indeed miss the event was if the promise was created during the execution of a message listener that runs before the one that creates window.test, i.e. when you have multiple callbacks listening to the same event. Therefore it's always better to install listeners immediately, especially when you are going to make a promise for it anyway. You can create the promise right away:

window.test = new Promise(resolve => {
    _worker.addEventListener('message', (event) => {
         resolve(event.data || "foo");
    }, {once: true});
});

Then use the promise everywhere (as many times as necessary). No need to store-and-cache the data value yourself when promises already do that for you.


Post a Comment for "What Happens When New Listener Is Attached When An Event Is Pending?"