0

Consider this snippet, where a function b gets a promise and calls itself when it is resolved in order to get another promise:

var a = function () {
    var timeout = 1000;

    let time_promise = new Promise((resolve, reject) => {
        let success = false;

        setTimeout(()=> {
        document.getElementById('log').appendChild(document.createTextNode("Called   "));
            resolve();
        }, timeout);
        });

    return time_promise;

};

var b = function() {
    a().then(()=>{
        //is the first b() released after this call?
        b();
    });
};

b();

code on jsfiddle

my question is: is the first call to b released after it called itself? Note the call to itself is inside a function called when then must be called.

Bertuz
  • 2,390
  • 3
  • 25
  • 50
  • It's released after `a()` call. https://jsfiddle.net/L62pjzq0/2/ – Alexey Ten May 13 '16 at 09:09
  • 1
    Call stacks are not preserved for scheduled functions. You might want read https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop – Felix Kling May 13 '16 at 13:32
  • 1
    Possible duplicate of [Building a promise chain recursively in javascript - memory considerations](http://stackoverflow.com/questions/29925948/building-a-promise-chain-recursively-in-javascript-memory-considerations) – Roamer-1888 May 14 '16 at 23:52

1 Answers1

1

There is no recursion. b doesn't call itself. The callback calls b and the callback is invoked after b has finished.

a better oliver
  • 26,330
  • 2
  • 58
  • 66
  • I'd still argue that it's still recursion, conceptually. A function doesn't have to directly call itself for being considered recursive (see mutual recursion), nor does it have to appear more than once in the stack (that's an implementation detail, see tail call optimization). But that might just be my opinion ;) – Felix Kling May 13 '16 at 13:30