如何检查作为Javascript参数传递的回调函数是否有参数?

Moh*_*sif 2 javascript callback node.js javascript-objects

我必须这样做

doSomething
    .then(success)
    .catch(failure);
Run Code Online (Sandbox Code Playgroud)

成功和失败是回调函数,它们将在运行时获得它们的价值(我正在尝试编写一个模块).

所以我必须知道作为回调发送的函数失败应该有一个参数.

因为回调应该是这样的

function(error) {
// An error happened
}
Run Code Online (Sandbox Code Playgroud)

JS中有没有这样做?或者任何可以进行此类检查的库?

编辑

只是为了澄清.我想要一个使用我的模块的用户(不是最终用户)发送一个函数作为一个参数,它将成为一个回调,我想检查发送的函数(将被回调)是否需要足够的参数.我理解由一个人用它来照顾它.但为什么不试试?

T.J*_*der 6

使用promise回调(你的thencatch处理程序),它们只会在被调用时传递一个参数,并且将始终传递该参数.(如果承诺遵守本机语义; jQuery Deferred并不总是这样.)

在一般情况下:

通常你不在乎,因为在JavaScript中,你可以调用一个参数少于或多于参数的函数.也就是说,这很好:

function foo(a) {
  console.log("a = " + a);
}
foo();        // Fewer arguments than params
foo(1, 2, 3); // More arguments than params
Run Code Online (Sandbox Code Playgroud)

您不关心的另一个原因是该函数可以使用参数,即使它没有为它们声明形式参数,也可以使用rest参数或arguments伪数组(您将看到为什么这个片段会记录foo.lengthbar.length暂时) :

function foo() {
  console.log("First argument: " + arguments[0]);
}
function bar(...rest) {
  console.log("First argument: " + rest[0]);
}
foo(1);                                    // First argument: 1
bar("a");                                  // First argument: a
console.log("foo.length = " + foo.length); // foo.length = 0
console.log("bar.length = " + bar.length); // bar.length = 0
Run Code Online (Sandbox Code Playgroud)

因此,只需定义您的API将调用回调函数,并执行此操作,并由API的用户来确保他们使用您正确调用它们的内容.

在这些重要的场合,你可以使用函数的length属性来知道它声明了多少个正式参数:

function foo(a) {
  console.log("a = " + a);
}
console.log(foo.length); // 1
Run Code Online (Sandbox Code Playgroud)

请注意,这将告诉您声明了多少正式参数...

  • ...不计算rest参数(...identifier)
  • ...只有第一个参数带有默认值(即使之后没有默认值)

例如:

function foo(a, b = false, c) { // b has a default value
  console.log("a = " + a);
}
console.log(foo.length); // 1, even though `c` has no default value,
                         // because `c` is after `b`
Run Code Online (Sandbox Code Playgroud)

function foo(a, ...rest) {
  console.log("a = " + a);
}
console.log(foo.length); // 1, because the rest parameter doesn't count
Run Code Online (Sandbox Code Playgroud)