我正在用NodeJs编写一个API包装器,并且正在尝试干净地处理来自http.get()的响应。问题的根源在于,我讨厌所有教程中不干净的编码风格,在这些教程中,回调方法是匿名定义的。
// Bad. Can get ugly if the handle function has multiple lines or nested callbacks
http.get("www.example.com", function(response){/* handle response */});
// Better. Follows clean-code guidelines. Code is more reusable. Etc
var handleResponse = function(response){
// handle response
}
http.get("www.example.com", handleResponse);虽然我更喜欢后者,但我似乎无法将额外的参数传递给handleResponse,特别是我希望handleResponse调用的回调。
我目前的做法是:
module.exports = function() {
return {
apiGet: function(url, callback) {
http.get(url, function(response) {
var result = handleResponse(response);
callback(null, result);
});
}
}
}我想要的东西(但不管用)
module.exports = function() {
var handleResponse = function(response) {
var result = handleResponse(response);
callback(null, result);
};
return {
apiGet: function(url, callback) {
http.get(url, handleResponse);
}
}
}这段代码的问题是在方法handleResponse()中没有定义回调。我似乎无法回避这件事。
我试过的东西。
// hoping extra parameters get passed to function. Nope.
return {
http.get(url, handleResponse, callback);
}
// Trying out a suggestion from a random blog I found while googling for an answer. Nope.
return {
http.get(url, handleResponse.bind({callback: callback});
}发布于 2015-07-14 02:28:59
如果您的函数的主要任务是做一些事情,然后将控制流传递给其他函数,那么也许您应该考虑编写一个handleResponse()函数,而不是编写一个makeResponseHandler()函数。基本上,使用一个函数工厂:
function makeResponseHandler (callback) {
return function (response) {
// deal with response here
callback(null, result);
}
};
return {
apiGet: function(url, callback) {
http.get(url, makeResponseHandler(callback));
}
}注意:如果仔细观察,实际上不是将makeResponseHandler传递给http.get(),而是调用makeResponseHandler()并将其返回给http.get()。
发布于 2015-07-13 22:16:08
所以我在this related thread中找到了一些有用的东西。
return {
http.get(url, function(response){ handleResponse(response, callback); });
}这似乎是一个合理的妥协。我可以将一个长匿名函数转换为一个小型匿名函数,该函数只需使用所需的信息调用我的显式函数。
在我谈这个之前,有没有人对我想要完成的事情有其他的建议?我一直在寻找最高级别的代码可读性。
发布于 2016-05-12 10:16:53
为什么不使用:
var req = http.get("www.example.com");
req.SOME_VARIABLE = "something";
req.on("response", function(res){
//Do something with req.SOME_VARIABLE
});https://stackoverflow.com/questions/31394416
复制相似问题