Lit Aiy Lit Aiy - 3 months ago 15
Node.js Question

Repeat this set of actions forever in node.js

I am using node.js. I have this function which uses promises to introduce delay between performing certain actions.

function do_consecutive_action() {
Promise.resolve()
.then(() => do_X() )
.then(() => Delay(1000))
.then(() => do_Y())
.then(() => Delay(1000))
.then(() => do_X())
.then(() => Delay(1000))
.then(() => do_Y())
;
}


What I want to do is to have this set of actions repeat itself forever. How can this be done in node.js?

//make following actions repeat forever
do_X()
Delay(1000)
do_Y()
Delay(1000)

Answer

Just use recursion

function do_consecutive_action() {
    Promise.resolve()
        .then(() => do_X() )
        .then(() => Delay(1000))
        .then(() => do_Y())
        .then(() => Delay(1000))
        .then(() => do_consecutive_action())
}