如何“不断尝试直到成功”使用事件驱动模型?
我正在编写如下所示的代码:
function someFunction()
{
doStuffWithCallback(function(success)
{
if(success)
{
...
// do stuff here
...
}
else
someFunction();
});
}
基本上,继续尝试“doStuffWithCallback”,直到回调收到绿灯。一般来说,这可以通过循环来完成,但是如何使用事件驱动模型来完成此操作,而不会在永远无法成功的情况下导致无限递归? (成功
可能取决于外部服务器之类的东西,所以如果它们宕机了,它就会一直是错误的)。
代码结构不能改动太多;由于我正在使用的 API,我必须使用回调来完成我想要的任务。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的事件驱动模型不应该如下所示:
您的事件驱动模型应该如下所示:
这样,您的事件调度机制是异步的,并且您根本不会有任何递归调用。
然后,因为您仍然不希望永远分派事件,所以您可能会在组件内部引入一些限制,以定义事件将被重新分派的次数。一个简单的整数变量就可以了。
至少,实现一个退避机制,每次回调失败时,在排队重复尝试之前,该机制可能会等待逐渐更长的时间间隔。
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.
您可以引入一个计数器,并使用
someFunction(1000)
调用它来尝试 1000 次。You could introduce a counter, and call it with
someFunction(1000)
to try 1000 times.