为什么要在http.createServer()中返回一个值呢?(Why bother returning a value in http.createServer())

我正在开展Learnnyounode研讨会,我对这个官方解决方案的片段感到好奇。

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

我只是好奇为什么他们懒得回复一个值。 你可以调用res.end(),它会按预期工作(正如我所期望的那样)。 看起来end()只是返回一个布尔值,但我不明白为什么你需要或想要返回任何东西。

I'm doing the learnyounode workshop and I'm curious about this snippet from one of the offical solutions.

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). It looks like end() is just returning a boolean value but I don't understand why you would need or want to return anything.

最满意答案

这个函数的返回值实际上并没有去任何地方,尽管理论上它可以:

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

据我所知, .createServer实际上并不是出于任何原因在内部执行此操作。 在这种情况下你想要使用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'); })

当然if / else可能会阻止继续执行该函数,但出于上述任何一个原因,您可以在回调函数中使用return 。

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. The reason why you would want to use return in this case would be to short circuit the function execution, e.g.

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.

更多推荐