递归调用异步函数 [英] Call asynchronous function recursively

查看:142
本文介绍了递归调用异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步函数,我想连续多次调用。
问题是倍数可能是几十万或几百万...

I have an asynchronous function that I want to call multiple times in a row. The problem is that "multiple" can be a few hundred thousand or millions...

显而易见的方法是从回调中调用相同的函数那:

The obvious way is to call the same function from the callback like that:

function foo()
{
    asyncBar(foo);
}

当然有一些逻辑可以阻止递归。问题是堆栈是否正在填充调用并且可能在某个时刻导致堆栈溢出?

Of course some logic is involved to stop the recursion. The question is whether the stack is filling with calls and may cause stackoverflow at some point?

推荐答案


问题是堆栈是否正在填充调用并且可能在某个时刻导致
stackoverflow?

The question is whether the stack is filling with calls and may cause stackoverflow at some point?

否。 如果 asyncBar()调用回调它是异步传递的,那么就没有堆栈构建。

No. If asyncBar() calls the callback it is passed asynchronously, then there is no stack build-up.

在你的代码中:

function foo() {
    asyncBar(foo);
}

这是正在发生的事情,一步一步:

here is what is happening, step-by-step:


  1. 首先调用 foo()

  2. 这个然后调用 asyncBar(foo)

  3. 因为 asyncBar 是异步的,意味着它启动一个异步操作(让我们假设它是一个http GET,但任何异步操作都会这样做)。启动异步操作,但 asyncBar()立即返回。

  4. 初始调用 foo( )返回并且堆栈完全展开。堆栈上不再有 foo()

  5. 调用 foo后的任何代码( )继续运行直到完成并返回事件循环。

  6. 同时异步操作将来会结束一段时间。这会在事件队列中调用你的回调函数。

  7. 当JS引擎完成执行其他Javascript(这意味着堆栈完全为空)时,它会将该事件从事件中拉出来排队并调用回调。

  8. 在这种情况下,回调函数是 foo 所以它调用该函数并开始遍历循环再次,回到第2步。

  1. First foo() is called.
  2. This then calls asyncBar(foo).
  3. Because asyncBar is asynchronous, that means it starts an asynchronous operation (let's suppose it is an http GET, but any async operation will do). That asynchronous operation is initiated, but then asyncBar() immediately returns.
  4. That initial call to foo() returns and the stack is completely unwound. There is no foo() on the stack any more.
  5. Any code after the call to foo() continues to run until it is done and returns back to the event loop.
  6. Meanwhile the asynchronous operation finishes some time in the future. That places a call to your callback in the event queue.
  7. When the JS engine is done executing other Javascript (which means the stack is completely empty), it pulls that event out of the event queue and calls the callback.
  8. In this case, the callback function is foo so it calls that function and starts the cycle all over again, right back to step 2.

没有堆栈积累。关键是异步回调在当前堆栈完成后被调用,解除并返回系统。

There is no stack build-up. The key is that asynchronous callbacks are called sometime later, after the current stack has finished, unwound and returned back to the system.

这篇关于递归调用异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆