0

I need to recursively call a function itself inside a .then() method. Something like this:

function poll(params) { 
    const returned_promise = read_from_backend(some_url, some_params);
    returned_promise
       .then(some_process_func)
       .then(r => {
            poll(some_params); // recursive call
        })   
}

poll(starting_params);

Is there a way to write this algorithm in a while loop, without blocking the main thread?

Jinghui Niu
  • 990
  • 11
  • 28

1 Answers1

-1

Here's a way to write the algorithm with a while loop. Since we're working with async code via Promises, we won't be blocking the main thread.

async function poll(params) {
    while (true) {
        await new Promise(resolve => setTimeout(resolve, 1000)) // perhaps sleep a bit between polls
        const returned_promise = read_from_backend(some_url, some_params);
        const r = await returned_promise.then(some_process_func)
    }
}

poll(starting_params);
richytong
  • 2,387
  • 1
  • 10
  • 21
  • 1
    This will produce an **Infinite loop** – Yves Kipondo Dec 03 '20 at 06:11
  • @richytong I think infinite loop is fine, but could you please give some thoughts on pros and cons of using while loops compared to a recursive call? – Jinghui Niu Dec 03 '20 at 13:08
  • If you're using node.js at least, you wouldn't be able to recurse forever since you'd run into the call stack limit eventually. With a while loop you don't have this issue since you're not recursing. This is a general argument for iterative vs recursive approaches. – richytong Dec 03 '20 at 15:46
  • [tail call optimization](https://stackoverflow.com/questions/310974/what-is-tail-call-optimization) would fix this in theory but I don't think Node.js at least has any plans to support it. From [this issue](https://github.com/nodejs/CTC/issues/3) – richytong Dec 03 '20 at 15:49
  • see [this question](https://stackoverflow.com/questions/23260390/node-js-tail-call-optimization-possible-or-not) for more info on node.js + tail call – richytong Dec 03 '20 at 16:05
  • 1
    I'm using the browser. Thanks for this explanation. – Jinghui Niu Dec 03 '20 at 22:59
  • @richytong I'm still study your code. Why do you include a 1000ms pause? – Jinghui Niu Dec 06 '20 at 07:36
  • @JinghuiNiu I included it arbitrarily. You can remove it if you'd like. – richytong Dec 06 '20 at 16:02