开发者

How to "keep trying until it works" with an event-driven model?

开发者 https://www.devze.com 2023-03-15 05:13 出处:网络
I\'m writing code that looks like this: function someFunction() { doStuffWithCallback(function(success) {

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:

  • Component dispatches an event
  • Application kernel receives event
  • Application kernel distributes event to registered handlers
  • A component registered as a handler may dispatch another event. In which case, repeat.

Your event-driven model should look like this:

  • Component dispatches an event
  • Application kernel receives event
  • Application kernel queues event
     
  • Next "tick", application kernel distributes all queued events to registered handles
  • A component registered as a handler may dispatch another event. In which case, repeat.

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.


You could introduce a counter, and call it with someFunction(1000) to try 1000 times.

function someFunction(countDown)
{
    doStuffWithCallback(function(success)
    {
        if(success)
        {
            ...
            // do stuff here
            ...
        }
        else if(countDown > 0)
            someFunction(countDown - 1);
    });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消