nodejs EventsEmitter, replace the last event handler with a new one

17 views Asked by At

I have a web service, the project and scope of problem itself is too big to paste, I will try to write small fragments of code to explain the situation, it seems to me that it is enough to explain the situation, and trigger the answer to anyone who experianced this issue.

On some edge cases, I must take immediate action, as well as other actions I want to do later in time, either on a timer or manual trigger.

I will refer to that code below, You could skip the code and use it afterwards for reference.

var EE=new EventsEmitter();
do_cleanup(){
//do a bunch of business logic and generate:
  var cleanup_result="good or bad job depands on expectation";
  EE.emit("cleanup",cleanup_result);
}

var daily=24*60*60*1_000;
setInterval(do_cleanup,daily);
app.get("/cleanup",(q,s)=>{do_cleanup();s.end("Done, Sir");});

app.get("/some_edge_case",(q,s)=>{
  s.end("OK Sir, taking care");
  //start web workers and follow the critical protocol
  EE.once("cleanup",(info)=>{
    //do the non critical protocol;
  })
});

app.get("/some_edge_case2",(q,s)=>{
  s.end("OK Sir, taking care");
  //start web workers and follow the critical protocol for 
  some_edge_case2
  EE.once("cleanup",(info)=>{
    //do the non critical protocol some_edge_case2;
  })
});

Now, assuming some_edge_case happens 1-20 times (or infinite times if some other microservice is wild), but I always want to run only the latest handler for edge case1, and the latest for edge case 2.

How can I replace the eariler handler with the new one?.

I couldn't just make EE.off("cleanup") before atteching the new one, since this will remove other listeners.

In real world I have many many on cleanup listeners, and I couldn't easily just make a new event for every listener, they should logically listen to the same command.

I would expect some associative parameter, so I could associate the handler with some string and have it replace that identifier on every call.

The program in question is also suffering from very high memory usage (causing slowness, GC, swap, and doesn't play well with neighbors) in this app, I suspect that (as a side effect, besides the logical intent) retaining only a single function and scope will help with memory too.

Is there any other pattern or unknown lib/parameter to do this, besides relying on global arrays to keep stack on my listeners (or neatly implementing my own EE class)?

0

There are 0 answers