Streams & Performance

Preview — 3 of 10 questions

What is the execution order in this Express application?

javascript
const express = require("express");
const app = express();

console.log("1");

app.use((req, res, next) => {
  console.log("2 - Middleware A");
  next();
  console.log("2 - Middleware A (after next)");
});

console.log("3");

app.use((req, res, next) => {
  console.log("4 - Middleware B");
  next();
  console.log("4 - Middleware B (after next)");
});

console.log("5");

app.get("/", (req, res) => {
  console.log("6 - Route handler");
  res.send("OK");
  console.log("7 - After send");
});

console.log("8");

app.listen(3000);

// Request: GET /
A1 → 3 → 5 → 8 → 2 → 4 → 6 → 7 → 2 (after next) → 4 (after next)
B1 → 2 → 3 → 4 → 5 → 6 → 7 → 8
C2 → 4 → 6 → 7 → 2 (after next) → 4 (after next)
D1 → 3 → 5 → 8 then 2 → 4 → 6 → 2 (after next) → 4 (after next)

What problem might occur with this database code?

javascript
const pool = new Pool({ max: 10 });

app.get("/api/data", async (req, res) => {
  const client = await pool.connect();
  
  try {
    const result = await client.query("SELECT * FROM users");
    res.json(result.rows);
  } catch (error) {
    res.status(500).json({ error: error.message });
    // Connection never released!
  }
});
ANo problem; code is fine.
BConnection pool exhaustion; connections not returned.
CDatabase will clean up automatically.
DOnly happens with old Node.js versions.

What will happen if you perform a blocking operation in an Express route?

javascript
app.get("/", (req, res) => {
  // Blocking operation
  let sum = 0;
  for (let i = 0; i < 10000000000; i++) { // 10 billion iterations
    sum += i;
  }
  res.json({ sum });
});
AEvent loop handles it efficiently.
BAll other requests are blocked until this computation completes.
CRequest is automatically moved to a worker thread.
DNo problem; Node.js is optimized.

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.