简体   繁体   中英

Exact nature of express.js "next()" parameter

I am very new to express.js and am reading through the documentation. I understand that the purpose of the next parameter in express middleware is to invoke the subsequent middleware function for the given route. I had assumed that next() was a function defined in the express API. However, the documentation specifically says the following: 在此处输入图片说明

Notice the call above to next(). 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 could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.

What confuses me about next is that it doesn't appear to be defined anywhere, and so the claim that it is not part of the API is odd. The only thing I can think of is that express automatically rewrites next to be the subsequent middleware function behind the scenes (passes it as the third argument to the first middleware callback function).

My question is essentially this-- I know what next does, but exactly is it?

The next parameter is a callback provided by Express. It's a function that takes one parameter which indicates whether the next middleware function should be proceeded to.

If you pass a non-null/non-undefined value to next it indicates an error and no further processing happens.

If you pass no parameter or null then the Express continues to the next thing it will do.

To answer your question, next is a callback function provided by Express that controls when Express should move along to the next step. Its implementation is internal to Express.

Note that if your middleware is finishing the request (say by calling res.json("done!") ) then you don't need to call next at all since there's nothing more to do.

As you noted, the name of the function is local at this point and can be called anything, but is usually called next .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM