0

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?

Aarni Joensuu
  • 711
  • 8
  • 19
  • Learn Node's event driven architecture and its `EventEmitter` class. A short tutorial here: [Event emitter](https://nodejs.dev/learn/the-nodejs-event-emitter) – h-sifat Jan 20 '22 at 09:59
  • *"I don't completely understand why"* Because processing the `request` stream is asynchronous. That's why you registering event handlers for `data` and `end`. Those functions will be called at some point in the future. Your other two `console.log` statements are not waiting for that. – Felix Kling Jan 20 '22 at 09:59

0 Answers0