0

I am having a hard time wrapping my head around what next is doing in this Express.js example and why it is used here.

This is the file where I am handling my routes.

 const express = require('express');
 const controller = require('../controllers/myappcontroller');
 const myroutes = express.Router();
 const apphelper = require('../services/appservices/apphelper');

 myroutes.get('/', apphelper.mycoolfunction, controller.index);

This is the contents of the apphelper.js file

require('isomorphic-fetch');


function mycoolfunction(req, res, next) {
  fetch('someurl')
  .then((fetchRes) => {
    return fetchRes.json();
  }).then((jsonFetchRes) => {
    res.locals.firstname = jsonFetchRes.contents.firstname[0].firstname;
    next();
  }).catch((err) => {
    console.log(err);
    res.locals.firstname = 'not available';
    next();
  });
}

module.exports = {
  mycoolfunction: mycoolfunction,
};

Why is there a "next" in the parameter and why are they used in the function? Is it there so that

Yahya
  • 706
  • 8
  • 23
craftdeer
  • 985
  • 5
  • 20
  • 36
  • 2
    It jumps to the next middleware. If you have `.get('/', func1, func2, func3)`, then `next()` in func1 will jump to func2, and `next()` in func2 will jump to func3. – Jeremy Thille Dec 01 '17 at 16:17
  • So in the example, if I did not have the "next" there, it would stop at `res.locals.firstname= 'not available';` and not do anything else? And because of the presense of "next", it runs the next parameter in line, in this case, `controller.index` correct? – craftdeer Dec 01 '17 at 16:59
  • 1
    Yep, that's exactly that – Jeremy Thille Dec 02 '17 at 06:32
  • great, thank you so much – craftdeer Dec 02 '17 at 15:17

1 Answers1

2

Simple, it tells your app to run the next middleware.