简体   繁体   中英

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

I am using the http module in node.js to read from url. The http.get function has this signature :

http.get(options[, callback])

The callback function takes a single argument, res. What can I do if I want to use extra objects/functions inside the callback? I can think of inlining the get call like so:

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

But if my callback gets long I want to declare it upfront somewhere:

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

And invoke myCallback like so:

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

But that seems super clumsy and only to get around the 1-arg callback restriction.

Are there better ways? Thanks!

you can use this code please,because myCallback return a function,then after get the resource,http will pass the res into xyz automatically.

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

You could use the arguments object.

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.

Quick example:

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

test1234('a', 'b');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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