Cyrille Cyrille - 4 months ago 11
Javascript Question

Loop on a promise indefinitely until rejection

I have a function that does some async work and returns a

Promise
, and I want to execute this function indefinitely until the promise is
reject
ed.

Something like the following :

doSomethingAsync().
.then(doSomethingAsync)
.then(doSomethingAsync)
.then(doSomethingAsync)
// ... until rejection


I made a little CodePen so I can test potential solutions : http://codepen.io/JesmoDrazik/pen/pbAovZ?editors=0011

I found several potential answers but nothing seems to work for my case.

If anyone has a solution, I'd be glad, because I just can't find anything !

Thanks.

Answer

You can do

(function loop(){
     doSomethingAsync().then(loop);
})();

But looking at your pen it's not clear where the rejection should come from. If you want to stop repeating an operation when the user clicks a button, you can change a state in the button handling and then do

(function loop(){
     doSomethingAsync().then(function(){
          if (!stopped) loop();
     });
})();
Comments