如何在 1-arg javascript 函数中使用 2 个参数?

How to use 2 arguments in a 1-arg javascript function?

我正在使用 node.js 中的 http 模块来读取 url。 http.get 函数有 this signature:

http.get(options[, callback])

回调函数只有一个参数,res。如果我想在回调中使用额外的 objects/functions 怎么办?我可以考虑像这样内联 get 调用:

outerFunction = function(xyz) {
  http.get(options, (res) => {
    // do stuff with xyz here
    xyz(res.blah);
  }
});

但如果我的回调变长,我想在某处预先声明它:

myCallback = function(xyz) {
  return function(r) { xyz(r.blah); };
}

并像这样调用 myCallback:

outerFunction = function(xyz) {
  http.get(options, (res) => {
    myCallback(xyz)(res);
  });
}

但这似乎非常笨拙,只能绕过 1-arg 回调限制。

有没有更好的方法?谢谢!

你可以使用这段代码,因为myCallback return一个函数,然后在获取资源后,http会自动将res传递给xyz。

outerFunction = function(xyz) {
   http.get(options,myCallback(xyz));
}

您可以使用 arguments 对象。

The arguments object is a local variable available within all functions. You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0.

快速示例:

function test1234(a){
    var args = arguments;
    console.log(args); // prints -> 0: "a", 1: "b"
}

test1234('a', 'b');