The Observer Pattern: Synchronous and Asynchronous Events
Learn about synchronous and asynchronous events in the Observer pattern.
We'll cover the following
Synchronous and asynchronous events
Similar to callbacks, events can also be emitted synchronously or asynchronously with respect to the moment the tasks that produce them are triggered. It’s crucial that we never mix the two approaches in the same EventEmitter
, but even more importantly, we should never emit the same event type using a mix of synchronous and asynchronous code, to avoid producing the same problems described in the “Unleashing Zalgo” section. The main difference between emitting synchronous and asynchronous events lies in the way the listeners can be registered.
When events are emitted asynchronously, we can register new listeners, even after the task that produces the events is triggered, up until the current stack yields to the event loop. This is because the events are guaranteed not to be fired until the next cycle of the event loop, so we can be sure that we won’t miss any events.
The FindRegex()
class we defined previously emits its events asynchronously after the find()
method is invoked. This is why we can register the listeners after the find()
method is invoked, without losing any events, as shown in the following code:
Get hands-on with 1400+ tech skills courses.