Óscar
Óscar5mo ago

Detect when the event loop is finished in a Worker

When Deno executes a script, once the script is finalized, the process is terminated. Is there any way to detect that inside a worker? I know I can call self.close() to terminate the worker, but I want to wait until all timers are closed (unawaited promises, etc) and the event loop is clean. Deno does it automatically in the main script, but I don't know if there's a way to detect this state inside a Worker.
3 Replies
Deno AI Helper
Deno AI Helper5mo ago
I wasn't able to find the answer to your question in the official Deno documentation. However, based on your message, there doesn't seem to be any obvious syntax errors or mistakes. It's important to note that the behavior you're describing—waiting for all timers to close and unawaited promises to settle before terminating—is not something that is typically exposed through a standard API in JavaScript environments. In Node.js, for instance, the process stays alive as long as there are pending asynchronous operations, but there isn't a built-in way to "detect" when the event loop is "clean" without manually tracking the operations. In Deno, and specifically within a Worker, you might need to implement your own tracking of asynchronous operations if you want to achieve a similar effect. This could involve keeping count of active operations and only calling self.close() when that count reaches zero. Please note that this advice is not based on the Deno documentation, and I would advise you to double-check the accuracy of this advice, possibly by experimenting with your code or seeking further insights from the Deno community.
bartlomieju
bartlomieju5mo ago
Afaik there's no way to do that. Web Worker spec is pretty lax about it.
Óscar
ÓscarOP5mo ago
Yep, that's what I was afraid of. Thanks anyway!