bubakazouba
bubakazouba

Reputation: 1683

how can I communicate with an anonymous function

My code is starting to have a lot of nesting and it's starting to be hard to maintain. I am trying to declare the callback functions as non-anymous functions and pass them as arguments.

all I am trying to do is to convert this code:

    http.createServer(function(clientReq,clientRes){
        var clientRequestHeaders=clientReq.headers;

        //example.com would give me a url that I need to send a GET request
        http.request({hostname:'example.com'}, function(res){
            var data='';
            res.on('data', function(chunk)){
                data+=chunk;
            });
            res.on('end',function(){
                http.request({hostname:data, headers: clientRequestHeaders}, function(res){});
            });
        });
    });//end createServer

to this:

    function func(res){
            var data='';
            res.on('data', function(chunk){
                data+=chunk;
            });
            res.on('end',function(){
                http.request({hostname:data, headers: clientRequestHeaders}, function(res){});
                                                     //^^^^ can't access headers now
            });
    }

    http.createServer(function(clientReq,clientRes){
        var clientRequestHeaders=clientReq.headers;

        //example.com would give me a url that I need to send a GET request
        http.request({hostname:'example.com'}, func);
    });//end createServer

so my question is: how to pass the clientRequestHeaders variable around?

and what if I needed to modify it too?

Upvotes: 0

Views: 52

Answers (1)

Louay Alakkad
Louay Alakkad

Reputation: 7408

You can use Function.prototype.bind

function callback(headers, res) {
  // ... your original anonymous function
}

http.createServer(function(clientReq,clientRes){
  var clientRequestHeaders = clientReq.headers;
  http.request({hostname:'example.com'}, callback.bind(null, clientRequestHeaders)); // <--
});

Or a dynamic function

function getCallback(headers)
  return function callback(res) {
    // ... your original anonymous function
  }
}

http.createServer(function(clientReq,clientRes){
  var clientRequestHeaders = clientReq.headers;
  http.request({hostname:'example.com'}, getCallback(clientRequestHeaders)); // <--
});

Upvotes: 1

Related Questions