DEV Community

Deepak Rajamohan
Deepak Rajamohan

Posted on • Originally published at Medium on

Node.js: Event handling patterns

Node.js ordered event handling with Async Iterators

Events in node.js have become a day to day used programming construct. Along with it comes the need for adopting various event handling patterns.

Usually there are multiple observers listening to an event from an object and node.js will notify all of them at the same time.

But sometimes the requirement might necessitate executing the observers in an order, instead of notifying all at the same time. This means we need to notify each observer asynchronously and wait for its response before executing the next.

With node version 10 we have the async iterators and the for-await key word to get this done.

In the below example, we have a publisher which emits various events. It has a map to correlate every registered event with an async iterator and a list of observers.

While the async-iterators are a pretty interesting topic by themselves here we simplify it by using an available iterator module, p-event .

The for-await in the above code block has now become a background listener and will loop over when ever a new event is added to the iterator.

Next, let’s add multiple observers for the events.

The subscriber above adds 10 observers for two events event1 and event2.

We expect now the event notifier to execute the observers in the order of addition.

Lets check what is the output when we execute the above code snippet.

We see that the event observers are executed in an order, though they have different execution times.

Top comments (0)