What are the boundaries of recursion?

前端 未结 2 672
南方客
南方客 2020-12-04 04:01

Given

let doAsynchronousStuff = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(\"abcdefg\"[Math.floor(Math.random()          


        
2条回答
  •  北海茫月
    2020-12-04 04:47

    I rewrote the code eliminating all non relevant stuff and using a style I feel is more readable and appeasing in this context.

    function doAsynchronousStuff()
    {
       return new Promise((resolve, reject) => 
       {
          setTimeout(() => {resolve("test")}, 0)
       })
      .then(console.log)
      .then(doAsynchronousStuff);
    }
    

    We should analyze the execution flow remembering that JS has an event loop, particularly

    • setTimeout posts its argument function to be executed on the next1 cycle of the event loop.
    • then posts its argument function to be executed on the next cycle of the event loop.

    The existence of the event loop is important because the function posting message onto it run-to-completion before the loop is re-entered.

    Also a good knowledge of promises is required, for example knowing that then returns a new promise.

    When doAsynchronousStuff is executed the Promise object is constructed and its argument function is called immediately.

    Execution stack                      Event loop messages
    
    doAsynchronousStuff
    Promise constructor
    Closure (resolve, reject)
    

    This is in turn calls setTimeout that post an event and returns.

    Execution stack                      Event loop messages
    
    doAsynchronousStuff                  resolve("test")
    Promise constructor
    Closure (resolve, reject)
    setTimeout
    

    The execution falls back to doAsynchronousStuff that set the continuations for the Promise objects but doesn't execute them of course. So in the end doAsynchronousStuff returns and we have a run-to-completion situation.

    Execution stack                      Event loop messages
    
                                         resolve("test")
    

    The event loop executes resolve("test") (or better the closure that contains it) which set the promise as resolved and schedule its continuation on the next cycle

     Execution stack                      Event loop messages
    
     resolve                              console.log
    

    resolve ends we have again a run-to-completion situation.

     Execution stack                      Event loop messages
    
                                          console.log
    

    console.log is executed. Actually, a function that calls console.log is executed, this function is set by the promise object when then is called.
    When console.log returns its promise resolves and the doAsynchronousStuff is posted on the event loop.

     Execution stack                      Event loop messages
    
     resolve                              doAsynchronousStuff
    

    When resolve ends we have a run-to-completion and doAsynchronousStuff is executed once again.


    Now I won't dig too much in the mathematical sense nor in the CS theoretical sense of the terms in the list in your question, doing such would have no practical benefits as I don't believe this is a theoretical question.
    I will instead limit myself to a programming point of view.

    By the time the second doAsynchronousStuff instance is called the first one is long gone (it run-to-completion).
    Basically the situation is equivalent to doing this

    let f = () => { console.log('hi!'); setTimeout(f, 0); }
    

    I wouldn't call this function recursive since recursion implies a destruction of a problem into smaller auto-similar parts.
    A recursive function doesn't have to call itself directly or doesn't have to "make the stack grow" but it must be defined in terms of itself.

    If it were like

    let f = () => { f(); }
    

    I'd call it (badly) recursive. So what is it?
    I'd like to say that a function is recursive in the programming sense if you can't complete it without completing all the calls to itself it makes.
    The first example can be completed without waiting for the subsequent invocations of f to complete, the second one instead cannot.
    In my mind I call the first version of f, scheduled.

    Regarding tail-call optimization, it has nothing to do with this.
    TCO transform a particular kind of recursion into a loop, it is a compiler optimization not a property of the code.
    The tail-call is a property of the code, but this code is not tail-call as it is not recursive in the first place.

    It is also not iteration in the programming sense (while in the theoretical sense it is) since iteration is achieved with specific constructs (like for, while, goto).
    The boundary is blurry here as iteration, recursion and scheduling overlaps.

    Finally this is certainly the case of a non-terminating procedure that happens to refer to itself.


    1 We make a simplification here, it has not to be the very next cycle, it is just a future cycle.

提交回复
热议问题