简体   繁体   English

不带参数的node.js next()中间件函数如何工作?

[英]How does node.js next() middleware function work without arguments?

Middleware functions have a signature function (req, res, next) , but in Express the next() call does not contain arguments. 中间件函数具有签名function (req, res, next) ,但是在Express中, next()调用不包含参数。 How is this so? 怎么了 See the following example from the sample documentation 请参阅示例文档中的以下示例

var express = require('express')
var app = express()

var myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000)

It certainly could be the case that a wrapping function is created that under-the-hood binds the arguments, allowing for a call with no additional parameters, but the documentation seems to indicate that the next parameter is called as-is, which does not make sense. 肯定是这样的情况:创建了一个包装函数,该函数在幕后绑定了参数,从而允许不带其他参数的调用,但是文档似乎表明next参数被称为“ as-is”,而不是说得通。

The docs describe the third argument, conventionally named next , as 文档将第三个参数(通常命名为next )描述为

Callback argument to the middleware function, called "next" by convention. 中间件函数的回调参数,按照惯例称为“ next”。

You can think of it similar to the conventional node.js callback-style argument provided to most async functions (without promises). 您可以认为它类似于大多数异步函数提供的常规node.js回调样式参数(无承诺)。 When your middleware function is done doing its sync or async work, it should call next to indicate to the express router that it is done executing. 当您的中间件功能完成其同步或异步工作时,它应调用next来向快速路由器表明已完成执行。 This argument could be called done or callback , as we often see in other node.js libraries and examples, but is called next to provide a hint to the developer that the middleware chain will continue execution (other middleware may be called after this one). 正如我们在其他node.js库和示例中经常看到的那样,可以将此参数称为donecallback ,但是next调用该参数是为了向开发人员提供一个暗示,即中间件链将继续执行(在此之后可以调用其他中间件) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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