I believe it is a security mechanism.
You can achieve the same result with just one addEventListener per event. My best guess is protection against memory leaks.
You also can only use two types of events: fetch and scheduled.
A limit of two is a natural approach from a security stand point.
Once the response is returned the worker stops running, I believe this is intended.
The first 2 work almost by-chance, because they are executed before the 3rd one. But I wouldn’t write this kind of code as it might be fragile. For example, if you had there instead of just console.log some async operation it might not finish it or run the code after it.
If I had code that returned a promise wouldn’t waitUntil guarantee that it get done? I understand that promises that aren’t passed to waitUntil before the end of the event handler won’t end up completing but in my example I don’t even get a chance to call waitUntil.
The waitUntil only waits for some async operation inside any of the handlers. But the handlers are not waiting for each other.
The reason the last one is not executed is that that cloudflare stops all execution once a response is returned. if the code inside the 3rd listener would take longer to execute, the 4rth handler might run as well.
Why are you trying to use multiple listeners? You could rewrite this code to:
I’m currently just trying to see if this works like the javascript I am used to. People switched to addEventListener from window.onload because onload only works with one function so I wondered if this worked the same way. The way it behaves now though seems a little inconsistent. It seems like the logic to exit the worker is that either all event listeners have run or a respondwith has resolved and all waitUntils have resolved. It seems like that “or” could easily be or maybe should be an “and”. I guess it doesn’t really matter in terms of how you are able to use workers though.
Also I don’t think that code example is the same. Your example makes the promise of each function complete sequentially.