I'm writing code that looks like this:
function someFunction()
{
doStuffWithCallback(function(success)
{
if(success)
{
...
// do stuff here
...
}
else
someFunction();
});
}
Basically, keep trying "doStuffWithCallback" until the callback receives the green light. Generally, this would be done with a loop, but how can I do this with an event-driven model without causing infinite recursion in the event that success is never reached? (success
may be dependent on things like external servers, so if they're down, it will continually be false).
The structure of the code cannot be changed much; I have to be using callbacks to accomplish what I want because of the API I'm using.
Your event-driven model should not look like this:
Your event-driven model should look like this:
In this way, your event dispatch mechanism is asynchronous, and you won't have any recursive calls at all.
Then, because you still don't want events being dispatched forever, you might introduce some limit internal to the component that defines how many times the event will be re-dispatched. A simple integer variable will do.
At the very least, implement a back-off mechanism that might wait for progressively longer intervals each time the callback fails, before queuing a repeat attempt.