Out of the blue synchronization issues arising from utilizing the nodejs events module

In my code, I am utilizing the Node Events module to execute a function asynchronously.

var events = require('events');
var eventEmitter = new events.EventEmitter();

eventEmitter.on('myEvent', f2);

function f1(x, y) {
    console.log('received', x, y)

    eventEmitter.emit('myEvent', x, y);
    eventEmitter.emit('myEvent', x, y);
    eventEmitter.emit('myEvent', x, y);

    console.log('finished')
}

var count = 0
function f2(x, y) {
    count++;
    console.log('from f2 function', x, y, count)
}

f1(1, 2)

The current output of this code snippet is as follows:

alok@alok-HP-Laptop-14s-cf3xxx:~/tmp/test-node$ node alok.js 
received 1 2
from f2 function 1 2 1
from f2 function 1 2 2
from f2 function 1 2 3
finished

However, I am expecting the following output:

received 1 2
finished
from f2 function 1 2 1
from f2 function 1 2 2
from f2 function 1 2 3

I am puzzled by why console.log('finished') is appearing last and the execution seems synchronous. Any thoughts on this?

Answer №1

That is the fundamental operation:

Whenever the EventEmitter object triggers an event, all connected functions for that particular event are executed synchronously.

[..]

Comparing Asynchronous and Synchronous

The EventEmitter runs all listeners in a synchronous manner based on the order of registration. This ensures events are sequenced correctly and helps prevent race conditions and errors in logic. If needed, listener functions can transition to asynchronous mode using the setImmediate() or process.nextTick() methods:

const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  setImmediate(() => {
    console.log('this happens asynchronously');
  });
});
myEmitter.emit('event', 'a', 'b');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Populate a pair of div elements using just one AJAX request

Currently, I am attempting to use the load() function to ajaxly load two separate divs, #follow-x and #follow-y, by clicking a button. The approach I have taken is as follows within the success function of my code snippet. However, this method does not see ...

Show values in an angular template using an array

I want to showcase values of an array using *ngFor const blockData = [ {text: sampleText1, array: [val1]}, {text: sampleText2, array: [val2, dat2]}, {text: sampleText3, array: [val3, dat3]} ] <div *ngFor="let data of blockData"> ...

node.js unable to reach module stored on local machine

I created a small module for my project in learnyounode, but I am having trouble accessing it. Do I need to call the function within the module file? This is how the module was written: ==> filter.js <== var fs = require('fs') , path=requ ...

Unveil Information with Underscore JS

I am attempting to showcase my data in a table using Underscore.js. Below is the div container class I am working with: <div id="container"></div> Upon window load, I have added an event listener: window.addEventListener("load", function(ev ...

Adding a characteristic to every item in an array of objects

Currently, I am utilizing Node.js along with Mongoose to interact with a MongoDB database and retrieve an array of objects from a specific collection. However, my aim is to add an additional property to each of these retrieved objects. Below, you can see t ...

Sending angularjs form data to nodejs Express (Failure in request)

Recently, I started learning AngularJS and decided to create a simple login feature using AngularJS on the front end and Nodejs on the server side. Security is not a priority for me at the moment, as I am focused on understanding how to make HTTP posts. I ...

Eliminate the unnecessary code repetition in my functions using Typescript

I have 2 specific functions that manipulate arrays within an object. Instead of repeating the same code for each array, I am looking for a way to create reusable functions. Currently, my functions look like this: setLists(): void { if (this.product.ord ...

Loop through the array while handling a promise internally and ensure completion before proceeding

I am currently working on populating a response array with Firestore snapshots and creating download links for stored files within each snapshot. Despite trying various solutions involving Promises, the response array consistently ended up being null. do ...

Strategies for temporarily storing values within md-list-item in AngularJS

I am attempting to populate a list with items using material icons. The issue is that the values are being added permanently when the material icon is clicked, disregarding the save and discard buttons at the bottom of the card. My goal is to add values te ...

rectangle/positionOffset/position().top/any type of element returning a position value of 0 within the container

While the height/position of the container is accurately displayed, attempting to retrieve the top position (or any position) of containing elements yields a return value of 0. Additionally, using .getBoundingClientRect() results in all values (top, left, ...

Session-based Authorization

I'm completely new to working with express.js, and I've been facing an issue while trying to create a session-cookie after logging in. Even though I can initiate the session and successfully log in, the session data doesn't carry over to the ...

Bring in all subdirectories dynamically and export them

Here is what I currently have: -main.js -routeDir -subfolder1 -index.js -subfolder2 -index.js ... -subfolderN -index.js Depending on a certain condition, the number of subfolders can vary. Is there a way to dynam ...

What is the best way to implement a recursive service call that is triggered automatically at regular intervals?

I came across this code snippet: us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); $interval(function () { us.isConnected() .then(function (msg) { er.msg = msg }, function (msg) { er.msg = msg }); }, ...

ES6 Promises have a curious ability to accurately retrieve values from custom JavaScript objects

I have developed a unique library that functions independently from the Promise API, yet achieves similar objectives. It utilizes window.requestAnimationFrame and fallbacks to setTimeout, having no similarities with Promises. Interestingly, it is compatibl ...

Vue.js has mysteriously stopped functioning

My Vue.js project suddenly stopped working and I've been trying to figure out the issue for hours with no luck. Here's an overview of my HTML file which includes dependencies and a table displaying data from users. <!DOCTYPE html> <html ...

Change the attribute to read-only upon modification of the dropdown value

I have a dropdown menu with four options. My goal is to make the "number" input field readonly if the user selects either "option3" or "option4" from the dropdown. <select id="dropdown"> <option value="option1">option1</option> ...

Guide to setting the connection string for connect-pg-simple

The example provided on https://github.com/voxpelli/node-connect-pg-simple illustrates the following code snippet: var session = require('express-session'); app.use(session({ store: new (require('connect-pg-simple')(session))(), ...

skip every nth element in the array based on the specified value

The Challenge I'm currently working on a graph that relies on an array of data points to construct itself. One major issue I've encountered is the need for the graph to be resizable, which leads to the necessity of removing certain data points ...

Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element: function draw(json) { if (json["leaf_text"]) { stroke(100) el ...

Clicking on a button in the Shield UI Grid Toolbar will apply filters to

Currently, I am working with a grid that utilizes a template for the toolbar. In this grid, there is a column labeled "Status." My goal is to filter the rows so that only those where the Status equals Request to Reschedule, Cancelled, Office Call Required, ...