I have created a Worker
in javascript that needs to loop indefinitely. Inside the loop, it needs to make several asynchronous calls and wait for them to complete before continuing on.
There are two immediate ways to do this that I can see that both seem to be fatally flawed:
1)
while(true) {
var promise = async_call();
while(!promise.isResolved()) { }
}
2)
var func = function() {
var promise = async_call();
promise.done(func);
}
func();
For #1, it falls apart because the inner while
loop potentially burns up a lot of cpu; and if the thread is not interruptable, (are javascript threads interruptable? I don't think they are), then the async_call
will never actually get a chance to complete, so we just get stuck in a loop.
For #2, it would work well if there was tail-call optimization, but I don't think any javascript implementations employ this, so it would quickly result in a stack overflow or other recursion limit.
Lastly, I need a way to signal to both loops when they should terminate. I can easily do this by putting a boolean stop
variable into the code, but, again, that relies on the worker thread being interruptable, such that I can set stop
to true.
Is there a design pattern that I have overlooked or am otherwise unfamiliar with here? How can I get my worker to execute as fast as possible without resorting to something like setInterval
paired with polling isResolved
?
Pattern 2 is perfectly fine. It will not end up in a stack overflow if the callback is really asynchronous (some Promise libraries enforce that), as the event will be executed with a completely new stack. Only if you would synchronously call func
you'd get the overflow, but you just synchronously register it as a callback.