简体   繁体   中英

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?

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)); // <--
});

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