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

71
Views
How to execute code in desired order in NodeJS?

My code is executing in the wrong order, and I don't completely understand why, nor am I able to fix it.

Sample code:

const router = require("express").Router();

function parse(request) {
  request.on("data", function(data) {
    console.log("handling data"); // expect these logs to occur first
  });
  request.on("end", function() {
    console.log("returning data"); // expect this log to occur second
  });
}

router.post("/", (request, response) => {
  let body = request.body;
  if (bodyNeedsParsing()) {
    body = parse(request);
    console.log("body parsed"); // expect this log to occur third
  }
  console.log("proceeding onward"); // expect this log to occur fourth
});

My expected execution order would produce logs as follows:

handling data
returning data
body parsed
proceeding onward

But instead what I'm seeing is:

body parsed
proceeding onward
handling data
returning data

This also naturally bricks the application. What is it that should be done differently?

about 4 years ago · Juan Pablo Isaza
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!