Request Relay · Level 4 of 7

Pass the baton with next()

Watch the order of the logs before and after each next() call.

const http = require('node:http');const chain = [  (req, res, next) => { console.log('a before'); next(); console.log('a after'); },  (req, res, next) => { console.log('b before'); next(); console.log('b after'); },  (req, res) => { console.log('handler'); res.end('ok'); },];function run(req, res, i) {  chain[i](req, res, () => run(req, res, i + 1));}const server = http.createServer((req, res) => run(req, res, 0));server.listen(0, async () => {  const { port } = server.address();  const r = await fetch(`http://localhost:${port}`);  console.log('client got ' + await r.text());  server.close();});

1. Predict the output

Tap the lines in the order you think they print.

  1. 1…
  2. 2…
  3. 3…
  4. 4…
  5. 5…
  6. 6…