Q

Random posts about ... stuff

View the Project on GitHub rMaxiQp/rMaxiQp.github.io

24 May 2020

Node.js Events

by Q

In computer programming, event-driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions (mouse clicks, key presses), sensor outputs, or messages from other programs or threads.

Differ from a typical procedural programming, event-driven programming defines action for each event.

Node.js core API is built around an asynchronous event-driven architecture using emitters to emit listeners to be called.

All emitters are instances of the EventEmitter class that exposes an eventEmitter.on() function that allows one or more functions to be registered to named events emitted by the object. Event names should be camel-cased strings.

When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. The called listeners’ returned value are ignored and will be discarded.

The eventEmitter.emit() method allows an arbitrary set of arguments to be passed to the listener functions. When the listener function is called, the standard this keyword will refer to the EventEmitter instance to which the listener is attached. However, such reference update does not apply to arrow functions.

The EventEmitter calls all listeners synchronously in the order in which they were registered. This ensures the proper sequencing of events and helps avoid race conditions and logic errors.

const EventEmitter = require('events');

const emitter = new EventEmitter();

emitter.on('event', () => { console.log('First Event') })

emitter.on('event', () => { console.log('Second Event') })

for (i = 0; i < 10; i++) {

    /* Output:
     * First Event
     * Second Event
     * First Event
     * Second Event
     * ...
     */
    emitter.emit('event')
}

Using setImmediate() or process.nextTick() methods can switch listener functions to an asynchronous mode of operation.

It is easy to produce an unhandled rejection when using async functions. The captureRejections option in the EventEmitter constructor or the global setting installs a .then(undefined, handler) handler on the Promise. This handler routes the exception asynchronously to Symbol.for('nodejs.rejection') method is there is one, or to 'error' event handler is there is none.

The 'error' events that are generated by the captureRejections behavior do not have a catch handler to avoid infinite error loops. Therefore, do not use async functions as ‘error’ event handlers.

References:

Updated: 12 June 2020
tags: Language - Web