4

I'm using request npm to get http pages. I have something like that

function callbackFunction1() {
  var p = 'foo';

  request(url, callbackFunction2);
}

function callbackFunction2(err, response, body){

}

How could I pass the variable p as parameter of the callbackFunction2?

Mazzy
  • 13,354
  • 43
  • 126
  • 207
  • You can put the p variable outside the first callbackFunction1, then use it, as a normal variable, inside callbackFunction2. – Adam M. Aug 30 '14 at 10:19
  • 1
    This will solve your problem: http://stackoverflow.com/questions/13851088/how-to-bind-function-arguments-without-binding-this – eguneys Aug 30 '14 at 10:24
  • 1
    What is `p` in this situation? Are you looking to simply completely replace the `body` parameter or are you looking to pass it in as an extra parameter? – James Aug 30 '14 at 10:31
  • I'm looking to pass an extra paramter – Mazzy Aug 30 '14 at 10:34

2 Answers2

5

I think you need to give all 3 parameters.

You can pass an anonymous function as second parameter like bellow

request(url, function(err, response, body){
    callbackFunction2(err,response, body, p);
});
Matthias Posch
  • 537
  • 6
  • 27
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • 1
    think you need to also take err and response as parameters in the anonymous callback function – Matthias Posch Aug 30 '14 at 10:21
  • 1
    the parameters of callbackFunction2 are three then I should pass four parameters – Mazzy Aug 30 '14 at 10:23
  • @Mazzy I got confused a bit, why should you pass 4 parameters, when the function expects just 3 parameters, how will you use that? – Mritunjay Aug 30 '14 at 10:26
  • the request callback function takes three parameters https://www.npmjs.org/package/request – Mazzy Aug 30 '14 at 10:28
  • @MatthiasPosch is correct that all three parameters followed by the fourth local parameter need to be passed to your original callback. It doesn't really make sense *not* to define your callback inline unless it's being reused by other callbacks to `request`. Here's a jsfiddle demonstrating: http://jsfiddle.net/jimschubert/56p9nxv5/, open the console to see the outputs. – Joseph Yaduvanshi Aug 30 '14 at 14:41
0

@facebook 's comment is they way to go.

Use bind

request(url, callbackFunction2.bind(p));
...
console.log(this); // p

Read @facebook 's link to see how to do it without messing this if it matters in your use case.

Community
  • 1
  • 1
rollingBalls
  • 1,808
  • 1
  • 14
  • 25