gpt4 book ai didi

javascript - 我如何与匿名函数通信

转载 作者:行者123 更新时间:2023-12-03 08:03:27 25 4
gpt4 key购买 nike

我的代码开始出现大量嵌套,并且开始变得难以维护。我试图将回调函数声明为非任意函数并将它们作为参数传递。

我想做的就是转换这段代码:

    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

对此:

    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

所以我的问题是:如何传递 clientRequestHeaders 变量?

如果我也需要修改它怎么办?

最佳答案

您可以使用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)); // <--
});

或者动态函数

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

关于javascript - 我如何与匿名函数通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34501238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com