I have an app that needs to run a function continuously. That function returns a promise. I want the app to wait until the promise is resolved before it starts the function again.
Additionally, my app needs a start
and stop
function that causes it to either start running the function, or stop it respectively.
I have a simplified example here:
class App {
constructor() {
this.running = false
this.cycles = 0
}
start() {
this.running = true
this._run()
}
stop() {
this.running = false
}
_run() {
Promise.resolve().then(() => {
this.cycles++
}).then(() => {
if (this.running) {
this._run()
}
})
}
}
module.exports = App
My problem is that when I use this, setTimeout
seems to give up on me. For example, if I run this:
const App = require("./app")
const a = new App()
a.start()
console.log("a.start is not blocking...")
setTimeout(() => {
console.log("This will never get logged")
a.stop()
console.log(a.cycles)
}, 500)
The output will be:
a.start is not blocking...
And then the code in the setTimeout
callback never gets called.
I can try starting running node
on my command line and typing directly into the REPL, but after I call a.start()
the terminal freezes up and I can no longer type anything.
This kind of thing seems like it should be a pretty common pattern. For example, Express lets you start/stop a server without these issues. What do I need to do to get that behavior?