我想使用Open Weather
地圖找到天氣,我有2種方法,findWeatherByLocation
和findWeatherByCity
。我假設JavaScript
不支持method overloading
,因此不支持2個不同的名稱。兩種方法都接受將被觸發的callback
函數,並執行相同的操作。如何避免附加片段中的JavaScript代碼重複?
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
?
感謝您的幫助提前。
我投票作爲題外話,因爲它屬於http://codereview.stackexchange.com/ –