Call asynchronous function recursively

前端 未结 3 1752
日久生厌
日久生厌 2020-12-11 17:30

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 obviou

3条回答
  •  难免孤独
    2020-12-11 17:46

    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.

提交回复
热议问题