I wrote a class cotaining the following CoffeScript code:
class SomeClass
# ...lots of other code...
runner: ->
process.nextTick =>
if @some_condition
@do_something_async()
@runner()
What it is supposed to do is to wait for @some_condition to be true. This basically works, however since it really quickly loops through all of this it causes heavy resource usage. How would I do this correctly?
Use events to decouple conditions and code that must run when those conditions are met.
Pattern is:
listen for an event and set a listener that would run when the event is fired
eventEmitter.on("myEvent", function () {
console.log("myEvent just happened");
});
when something in your code can make your condition become true, check for it and fire an event accordingly:
doSomething();
something++;
if (something > max_something) {
eventEmitter.emit("myEvent");
}
Instead of having a loop that waits for something to be true, just make a callback function and pass that in to the function that is running long and call the callback when the process is done.