Reputation: 508
I'm having trouble wrapping my head around the concept of the next() function in express.js. I guess my first question would be is next() an express.js only function? My second question would be, in the example below what does next do? After the console function, it goes to the next function that is called after? I'm so confused.
var cb0 = function (req, res, next) {
console.log('CB0');
next();
}
Upvotes: 3
Views: 1833
Reputation: 1075785
With Express (and other similar systems), each request passes through a series of middleware functions (like your cb0
). Each of those has a chance to do something with the request.
Since the thing a middleware function does may be asynchronous (for instance, reading a file, querying a database, etc.), Express can't just directly call the next bit of middleware after calling the previous one. So instead, it passes the middleware function a function, next
, which that middleware uses to say "I'm done, run the next step." (In the Express version, you can also pass an argument to next
, as Aikon Mogwai points out: If you pass it an Error
, it triggers error handling for the route. If you pass it "route"
, it jumps to the next router, etc.).
So the concept of a next
function isn't specific to Express, but the specific use in that example is.
Here's a much simplified example not using Express, but demonstrating the sort of thing it does with middleware functions when handling a request:
const app = {
middleware: [],
use(callback) {
this.middleware.push(callback);
}
};
app.use((req, res, next) => {
console.log("First handler synchronous part");
setTimeout(() => {
console.log("First handler async part finished");
next();
}, 800);
});
app.use((req, res, next) => {
console.log("Second handler is entirely synchronous");
next();
});
app.use((req, res, next) => {
console.log("Third handler synchronous part");
setTimeout(() => {
console.log("Third handler async part finished");
next();
}, 800);
});
// Code handling an incoming request
function handleRequest(req, app) {
// Copy the handlers
const middleware = app.middleware.slice();
// Create a "response"
const res = {};
// Call the handlers
let index = 0;
next();
function next() {
if (index < middleware.length) {
// Call the handler, have it call `next` when it's done
middleware[index++](req, res, next);
} else {
console.log("Request completed");
}
}
}
handleRequest({}, app);
It's probably worth mentioning that this manual-style of asynchronous middleware handling has been replaced with promises in Koa.js, which is a new(er) framework from the same people who did Express.js. With Koa, you make your callbacks async
functions, and Koa's internals wait for the promise the async
function returns to settle and then acts on the result of it setting (e.g., rejection or fulfillment, the value it fulfills with, etc.).
Upvotes: 5
Reputation: 1077
var express = require('express')
var app = express()
var CB0 = function (req, res, next) {
console.log('CB0')
next()
}
app.use(CB0)
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000)
Each and Every time app receives a request and prints the message "CB0" console in terminal window.
The middleware functions that are loaded first are also executed first.
The middleware function CB0 simply prints a message, then passes on the request to the next middleware function in the stack by calling the next() function.
Upvotes: 2
Reputation: 4453
The next()
function requests the next middleware function in the application. The next()
function is not a part of the Node.js or Express API, but it is the third case/argument which is passing to the middleware function. The next()
function could be named anything, but by convention, it is always named "next". To avoid confusion, always use this convention.
For more info, you can visit the official tutorial of express
Upvotes: 2
Reputation: 745
Next is used to pass control to the next middleware function. If not the request will be left hanging or open. Calling this function invokes the next middleware function in the app. The next() function is not a part of the Node.js or Express API but is the third argument that is passed to the middleware function.
Upvotes: 3