就像现在一样,Node HTTP 请求的回调必须是请求中的匿名函数,就像这样......
http.request(params, function(res){
let data = "";
res.on("data", function(chunk){
data += chunk;
});
res.on("end", function() {
console.log(data);
});
}).end();
我想将回调从相同或不同的文件中分离成它自己声明的函数......就像这样......
function handleData(res) {
let data = "";
res.on("data", function(chunk){
data += chunk;
});
res.on("end", function(){
console.log(data);
});
}
https.request(params, handleData(res));
是否有可能做到这一点?任何地方都没有明确的答案。我觉得好像我是第一个尝试这个的人。在此先感谢您的时间!
它可以是这样的:
function handleResponse(res) {...yourcode...};
http.request(params, handleResponse).end();
或这个:
const handleResponse = function (res) {...yourcode...};
http.request(params, handleResponse).end();
或者
const handleResponse = res => {...yourcode...};
http.request(params, handleResponse).end();
或者
const handleResponse = res => {...yourcode...};
const request = http.request(params);
request.end();
request.on('response', handleResponse);
JavaScript 和 Node.js 非常灵活。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句