简体   繁体   English

为什么要麻烦在http.createServer()中返回值

[英]Why bother returning a value in http.createServer()

I'm doing the learnyounode workshop and I'm curious about this snippet from one of the offical solutions. 我正在进行learningyounode研讨会,我对其中一种官方解决方案的摘要感到好奇。

var server = http.createServer(function (req, res) {
  if (req.method != 'POST')
    return res.end('send me a POST\n')
})

I'm just curious why they bother returning a value at all. 我很好奇他们为什么不愿意返回一个值。 You could just call res.end() and it will work as expected (as I expect anyway). 您可以只调用res.end(),它将按预期运行(无论如何我还是希望如此)。 It looks like end() is just returning a boolean value but I don't understand why you would need or want to return anything. 看起来end()只是返回一个布尔值,但我不明白为什么您需要或想要返回任何东西。

The function you pass to http.createServer is added to an EventEmitter instance as an listener for request event . 传递给http.createServer的函数将作为请求事件的侦听器添加到EventEmitter实例。

The return value returned by listeners passed to EventEmitter are ignored, proof . 传递给EventEmitter的侦听器返回的返回值将被忽略, 证明

So the only benefit of using return statement in this case is for returning earlier and to ignore the rest of the function in case it exists, as was said by Explosion Pills . 因此,在这种情况下使用return语句的唯一好处是,如Explosion Pills所述,在更早返回时忽略该函数的其余部分(如果存在)。

The return value of this function doesn't actually go anywhere although in theory it could: 尽管从理论上讲,此函数的返回值实际上不会移到任何地方:

http.createServer = function (cb) {
    if (cb()) { /* do something */ }
};

As far as I know, .createServer doesn't actually do this internally for any reason. 据我所知, .createServer实际上不会出于任何原因在内部执行此操作。 The reason why you would want to use return in this case would be to short circuit the function execution, eg 在这种情况下,您要使用return的原因是使函数执行短路,例如

var server = http.createServer(function (req, res) {
  if (req.method != 'POST')
    return res.end('send me a POST\n')

  res.end('POST sent\n');
})

Of course an if / else could prevent continuing execution of the function anyway, but you can use return in callback functions for either of these reasons. 当然, if / else可能仍然阻止函数继续执行,但是出于上述两个原因之一,您都可以在回调函数中使用return

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

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