shapeare
shapeare

Reputation: 4233

How to process socket.io events in their incoming order

I have the following setup:

async MyFunction(param) {
    //... Do some computation
    await WriteToDB()
}

io.on('connection', (socket) => {
    socket.on('AnEvent', (param) => MyFunction(param))
})

When an event comes in, it calls an asynchronous function which does some computation and in the end write the result to a database with another asynchronous call.

If MyFunction doesn't have an asynchronous call to write the database in the end, for example

MyFunction(param) {
    //... Do some computation
}

then it is obviously that all events will be processed in their incoming order. The processing of the next event will only start after the processing of the previous one finishes. However, because of the asynchronous call to the database, I don't know if those incoming events will still be fully processed in order. I am afraid that the processing of the next event starts before the previous await WriteToDB() finishes. How do I change the code to fully processing them in order?

Upvotes: 0

Views: 799

Answers (1)

typicallearner
typicallearner

Reputation: 256

You are correct that there's no guarantee that incoming events will be processed in the order.

To achieve what you are asking, you would need a "Message Queue" that will periodically check for new messages and process them one by one.

const messageQueue = [];

// SocketIO adding Message to MessageQueue
const eventHandler = (message) => {
  messageQueue.push(message);
}

const messageHandler = () => {
  if (messageQueue.length === 0) {
    return;
  }

  const message = messageQueue.shift();

  // Handle Message

  // If successful, ask for next message
  return messageHandler();
}

Of course, my example is pretty naive, but I hope it will give you a general idea of how what you are asking is accomplished.

If you are finding yourself needing a more robust message queue, Look into RabbitMQ, BullMQ, Kafka

Upvotes: 1

Related Questions