Call asynchronous function recursively

泄露秘密 提交于 2019-11-28 08:11:12

问题


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?


回答1:


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

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

In your code:

function foo() {
    asyncBar(foo);
}

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

  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.




回答2:


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

If the method is asynchronous, then you won't get stackoverflow at all.

check this example below

function f1(n)
{
   if (n > 0 ) 
   {
       callAsynch(n, function(n){
          f1(n-1)
       });
   }
}

This callAsynch could be an Ajax call (or anything that is asynchronous) which takes a callback method as a parameter.

It is not pilling on the stack since each call ends with a call to an asynch method which is not returning the value back to this method, rather simply appending a task (calling f1(n-1)) to the queue after it is done.




回答3:


No stackoverflow in case of async calls.
Also, You can use async module's during method link, for recursively calling a async function.



来源:https://stackoverflow.com/questions/37405034/call-asynchronous-function-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!