Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!