简体   繁体   中英

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

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);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM