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?