gpt4 book ai didi

javascript - 这是如何运作的? Express 中使用的可选第一个参数 (err, req, res, next) 或 (req, res, next)

转载 作者:IT老高 更新时间:2023-10-28 23:10:56 26 4
gpt4 key购买 nike

使用 Express/Connect,我可以设置任何一种格式的中间件功能:

function(req, res, next) // first argument will be a request

或者

function(err, req, res, next) // first argument will be an error

从 Express、Connect 退回到基本的 JavaScript:我不明白这怎么可能有一个可选的第一个参数

如何表达知道我的函数将首先接受一个 err 对象?我认为要使这成为可能,结构必须如下所示:

function(req, res, next, err)

我在这里缺少一些基本的东西吗?是否可以查询一个函数需要多少个参数?

编辑:感谢以下回答。但是中间件函数是传递给express的,所以arguments变量是无效的。虽然 length 是正确的......我想我已经想通了,最好确认是否是这种情况。示例如下:

var fn;

fn = function (one, two) {};
console.log(fn.length); // 2

fn = function (one, two, three) {};
console.log(fn.length); // 3

最佳答案

I think I have figured it out, would be good to have confirmation to whether this is the case

var fn;

fn = function (one, two) {};
console.log(fn.length); // 2

fn = function (one, two, three) {};
console.log(fn.length); // 3

是的,没错。 Function 实例的 length 属性是它拥有的形式参数(声明的参数)的数量。这隐藏在 Section 13.2 中规范的第 14 步和第 15 步。

因此,调用函数的代码很容易检查 fn.length 并将可选的第一个参数传递给它,或者不传递给它,这取决于它。当然,这确实意味着完全可以编写一个 处理四参数版本的函数,但通过使用 arguments 而不是形参来欺骗框架。所以你不会那样做。 :-)

(很抱歉第一次误读您的问题。)

关于javascript - 这是如何运作的? Express 中使用的可选第一个参数 (err, req, res, next) 或 (req, res, next),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8431186/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com