【发布时间】:2016-08-13 07:46:40
【问题描述】:
我正在尝试使用Open Weather 地图查找天气,我有两种方法,findWeatherByLocation 和findWeatherByCity。我假设JavaScript 不支持method overloading,因此有两个不同的名称。这两种方法都接受callback 函数,该函数将被触发并执行相同的操作。
function findWeatherForCity(senderID, city, countryCode, callback) {
//Lets configure and request
request({
url: constants.OPEN_WEATHER_MAP_BASE_URL, //URL to hit
qs: {
q: city + ',' + countryCode,
appid: constants.OPEN_WEATHER_MAP_API_KEY
}, //Query string data
method: 'GET', //Specify the method
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
let weather = getWeatherReport(JSON.parse(body));
callback(weather ? weather : null);
}
else {
console.error(response.error);
callback(null);
}
});
}
/*
lat, lon coordinates of the location of your interest
* http://openweathermap.org/current
*/
function findWeatherForLocation(senderID, location, callback) {
//Lets configure and request
request({
url: constants.OPEN_WEATHER_MAP_BASE_URL, //URL to hit
qs: {
lat: location.lat,
lon: location.lon,
appid: constants.OPEN_WEATHER_MAP_API_KEY
}, //Query string data
method: 'GET', //Specify the method
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
let report = getWeatherReport(JSON.parse(body));
callback(report ? report : null);
}
else {
console.error(response.error)
callback(null);
}
});
}
如您所见,function(error, response, body) 在两个地方都做同样的事情。如果我创建一个单独的function(error, response, body),这对于findWeatherByCity 和findWeatherByLocation 都是通用的,我该如何触发callback?
提前感谢您的帮助。
【问题讨论】:
-
我投票结束这个问题,因为它属于codereview.stackexchange.com
标签: javascript callback overloading