Avoid recursive in promise-based loop?

As a simple sample program, I have a node script that constantly connects the server and wants this program to run for a long time.

The program is configured as a ping function that returns a promise object. A promise is allowed or rejected based on whether ping worked or failed.

I want this function to work in a loop, so regardless of whether ping is successful or not, the next ping is then launched after a certain time after the previous request has been resolved.

The problem is not the problem itself, but I am worried about my implementation. I believe that this will lead to a stack overflow in the end.

Here is some code to find out what is going on:

function doPing(host) {
    // returns a promise object.
}

function doEvery(ms, callback, callbackArgs) {

    setTimeout(function() {

        callback.apply(null, callbackArgs)
            .always(function() {

                doEvery(ms, callback, callbackArgs);

            });

    }, ms);

}

doEvery(1000, doPing, [host]);

, :

? , promises?

+4
1

. setTimeout - : , , . doEvery setTimeout, , .

, :

  • : [global scope] -> doEvery -> setTimeout
  • : [event loop] -> [handle timer] -> [closure #1 in doEvery] -> callback.apply -> doPing
  • : [event loop] -> [handle network] -> promise.resolve -> [closure #2 in doEvery] -> doEvery -> setTimeout
  • -: [event loop] -> [handle timer] -> [closure #1 in doEvery] -> callback.apply -> doPing

, , , , . ( - ping), , .

+2

All Articles