最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Question about the next() function in expressjs - Stack Overflow

programmeradmin5浏览0评论

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();
}

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();
}
Share Improve this question edited Apr 22, 2019 at 14:24 Hasta Dhana 4,7197 gold badges20 silver badges27 bronze badges asked Apr 22, 2019 at 12:55 noobcoderiamnoobcoderiam 5084 silver badges20 bronze badges 1
  • is next() an expressjs only function - no, any javascript code can have a function called next ... but next is just "conventional" name for that third argument in express - your code above would be equally valid if written var cb0 = function (req, res, frank) { console.log('CB0') frank() - read this middleware documentation for the uses of this callback – Jaromanda X Commented Apr 22, 2019 at 13:00
Add a ment  | 

4 Answers 4

Reset to default 5

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 ining 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 pleted");
    }
  }
}

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.).

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.

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

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.

发布评论

评论列表(0)

  1. 暂无评论