Dealing with asynchronous tasks in JavaScript

I am currently delving into the world of Node development and struggling to grasp the asynchronous nature of JavaScript and Node.js. My project involves creating a microservices backend web server using Express in the gateway service, which then translates REST requests into a series of messages published through RabbitMQ's async messaging module (amqplib). These messages are subscribed to by other services for processing and responding accordingly.

Here is an excerpt of my service responsible for handling asynchronous requests from the gateway:

amqp.connect('amqp://172.17.0.2', function(err, conn) {
  console.log("connection created");
  conn.createChannel(function(err, ch) {
    console.log("channel created");
    var exchange = 'main';

    ch.assertExchange(exchange, 'topic', {durable: true});

    ch.assertQueue('', {exclusive: true}, function(err, q) {
      console.log(' [*] Waiting for logs. To exit press CTRL+C');

      ch.bindQueue(q.queue, exchange, "VENUE_TOPIC.PENDING_STATUS.*.*");

      ch.consume(q.queue, function(msg) { 
        console.log(" [x] %s:'%s'", msg.fields.routingKey, msg.content.toString());
        var pending_event = JSON.parse(msg.content.toString())
        console.log(pending_event.payload.id == 2)
        console.log(pending_event.payload.id)
        if (pending_event.payload.id == 1) { 
          var venue = getVenueByID(pending_event.payload.id);
          const approved_event = new Event("VENUE_TOPIC", "APPROVED_STATUS", false, "READ_METHOD", {"venue":venue});
          var key = approved_event.getMetaAsTopics();

          var msg = Buffer.from(JSON.stringify(approved_event.getEventAsJSON()));

          ch.assertExchange(exchange, 'topic', {durable: true});
          ch.publish(exchange, key, msg, {persistent: true});
          console.log(" [x] Sent '%s'", msg);        
        } else if (pending_event.payload.id == 2) {
          sleep(10000); //this function checks the OS's clock to count time in ms
          var venue = getVenueByID(pending_event.payload.id);
          const approved_event = new Event("VENUE_TOPIC", "APPROVED_STATUS", false, "READ_METHOD", {"venue":venue}); 
          var key = approved_event.getMetaAsTopics();

          var msg = Buffer.from(JSON.stringify(approved_event.getEventAsJSON()));

          ch.assertExchange(exchange, 'topic', {durable: true});
          ch.publish(exchange, key, msg, {persistent: true});
          console.log(" [x] Sent '%s'", msg);
        }
      }, {noAck: true});
    });
  });
});

Imagine having two incoming requests, one lengthy and the other quick. If the long request arrives before the short one, there will be a delay due to the nature of the long process taking precedence. In this scenario, ID === 2 represents the long process while ID === 1 symbolizes the shorter one.

Is there a way to handle both requests concurrently without letting the lengthier operation hold up the quicker one until completion?

Answer №1

Unfortunately, my SO reputation isn't sufficient for commenting, but I will do my best to offer valuable insights.

If the sleep function refers to the npm package found here, then the behavior you are experiencing is expected - known as blocking behavior. If you intend to execute non-blocking tasks (such as web requests) within your consume function, Node will continue processing messages without interruption. However, if your task involves intensive CPU work that blocks processing of incoming messages, it's best to delegate this work to a separate worker.

Consider using the following code snippet for a "non-blocking" sleep function:

setTimeout(() => {
    var venue = getVenueByID(pending_event.payload.id);
    const approved_event = new Event("VENUE_TOPIC", "APPROVED_STATUS", false, "READ_METHOD", {
        "venue": venue
    });
    var key = approved_event.getMetaAsTopics();

    var msg = Buffer.from(JSON.stringify(approved_event.getEventAsJSON()));

    ch.assertExchange(exchange, 'topic', {
        durable: true
    });
    ch.publish(exchange, key, msg, {
        persistent: true
    });
    console.log(" [x] Sent '%s'", msg);
}, 10000);

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

Error: The login is invalid due to authentication failure with code 535 5.0.0

I'm currently working on setting up Outlook calendar events by integrating a mailing service with my project. I'm using the Express framework and Mongoose queries for this purpose. Below is the code snippet I have implemented: var _ = require(& ...

Populating a clickable list and form with a complex JavaScript object

I have a code snippet that takes an unstructured String and parses it into a JavaScript object. My next step is to integrate it into a web form. You can check out the demo here. The demo displays the structured object hierarchy and showcases an example of ...

Can Vuejs functions be triggered using a jQuery event trigger?

I am currently attempting to trigger a change event within a Vue component. Within the component template, there is a select element. When I try to use jQuery to trigger a change event on this element, the Vue component does not seem to detect it. Here i ...

Is it feasible to utilize the translate function twice on a single element?

Using Javascript, I successfully translated a circle from the center of the canvas to the upper left. Now, my aim is to create a function that randomly selects coordinates within the canvas and translates the object accordingly. However, I'm encounter ...

Utilizing jQuery AJAX to transfer files from the client side in .NET platform

I need to upload files from the client side using a jQuery Ajax function to a location on a different server, rather than sending them to my application's web server. This is to prevent unauthorized or virus-infected uploads to the application web ser ...

Is incorporating re-routing into an action a beneficial approach?

My main concern involves action design strategies: determining the best timing and method for invoking actions. In my project using Mantra (utilizing React for the front-end and Meteor's FlowRouter for routing), there is a UI component that includes ...

Tips for customizing the font color in Material UI Typography

Is it possible to change the color of only this text to red? return <Typography style={{ color: 'red' }}>Login Invalid</Typography> I came across this online solution, but I am unsure how to implement it as there is no theme={color ...

Firebase response comes back as a successful 200 code, however the array returned

I've been working on a project involving Firebase and Firebase functions. Right now, I'm struggling to retrieve documents from a collection called 'items'. When I try to make a GET request, all I get is a 200 status code with an empty r ...

`What can be done if ng-if is not responding?`

I'm facing an issue where I want to display a link <a href> only when a certain condition is met, but the link doesn't show up as expected. I have already attempted to experiment with changing the position of the code (inside or outside of ...

Can anyone assist with troubleshooting the font size issue for a JavaScript tooltip on Joomla 1.5 with CK Forms?

My Joomla 1.5 site has CK Forms installed and is functioning properly, except for one issue: the tooltip on the captcha is not displaying correctly. It appears in a tiny 1px font size. Even though I have tried debugging using Firebug and confirmed that the ...

The PDFKIT feature ensures that any overflowing data in a row is automatically moved to a new page

A function in my code generates a row of data based on an array. It works perfectly fine for the first page, but as soon as the data overflows somewhere around doc.text("example",70,560), it jumps to the next page. The issue arises when the Y coo ...

Editing XHTML on the fly

Is there a tool available for non-technical individuals to edit hard-coded content in XHTML? I am interested in a solution similar to the integration of Pagelime with jEditable. Currently, my website is static and I am seeking a way for one person to log ...

When attempting to capture an element screenshot as PNG, a TypeError occurs indicating that the 'bytes' object is not callable

Can someone please help me figure out how to save a screenshot of a specific element in Selenium using Python3? Here is the code I am trying: from selenium import webdriver import pyautogui as pog import time options = webdriver.ChromeOptions() options ...

The benefits of using Node.js for asynchronous calls

Each time a new data is added or existing data is updated, the variables new_data and updated_data will increment accordingly. However, when attempting to output the total count of new_data and updated_data at the end of the code, it always shows as 0. H ...

What is the best way to change the location of a jQuery Mobile global popup?

I have a jQuery Mobile global popup that is initially empty and generated dynamically. I am utilizing the beforeposition event to detect when the popup opens. At this point, I load a configuration file or content file, create the content, and then add it t ...

Is there a way for me to extract and showcase the initial 10 items bearing a particular class name from a different html document on my homepage?

I am looking to extract a list of movies from an HTML file titled "movies.html". The structure of the file is as follows: <div class="movie">Content 1</div> <div class="movie">Content 2</div> <div class=" ...

Troubleshooting: Why the TableTools basic usage example is not functioning as

After replicating the code from http://datatables.net/release-datatables/extensions/TableTools/examples/simple.html in my Visual Studio project, I organized the files by saving two css files as style1.css and style2.css, along with three js files named sc ...

Exploring the world of React-Bootstrap elements and properties

I'm currently diving into a Bootstrap home project and it's my first time working with Bootstrap. I came across a tag that has an 'inverse' attribute among others like 'fixedTop', 'fluid', and 'collapseOnSelect& ...

Node is currently posing a challenge for the installation of packages

I am currently facing an issue while setting up my raspberry pi 3. I am attempting to install and execute a node code, but I encountered a problem during the installation of packages using npm. After trying multiple times with different versions of node ( ...

Adjusting the date format within an AJAX success callback: alter how the date is displayed

Attempting the following code: var second_date = moment(currentdate).format('DD-MM-YYYY'); The result is: Uncaught Reference Error: moment is not defined. success: function(response){ var len = 0; if(response != n ...