我正在使用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()中未定义回调函数callback。我似乎无法解决这个问题。
我尝试过以下几件事:
// 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});
}