From 53026c94b47e5702cbb231b5d5882948b93c540d Mon Sep 17 00:00:00 2001 From: Gerome Matilla Date: Fri, 12 Jun 2020 15:32:02 +0800 Subject: [PATCH] modularize fetching openweathermap data --- js/weather-screen.js | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/js/weather-screen.js b/js/weather-screen.js index dc88161..7b5611f 100644 --- a/js/weather-screen.js +++ b/js/weather-screen.js @@ -146,21 +146,30 @@ class WeatherScreen { this._setWeatherValue(wLoc, wDesc, wIcon, rise, set, upd); } - getWeatherData = (appID, cityID, units) => { - const requestString = `https://api.openweathermap.org/data/2.5/weather?APPID=${appID}&id=${cityID}&units=${units}`; + _fetchOpenWeatherMapDate = (requestStr, callback) => { + + const requestString = requestStr; const request = new XMLHttpRequest(); request.open('GET', requestString, true); request.onload = e => { if (request.readyState === 4 && request.status === 200 && request.status < 400) { - this._tempSymbol = (units === 'metric') ? '°C' : '°F'; - this._processWeatherData(JSON.parse(request.response)); + callback(JSON.parse(request.response)); } else { this._setErrValue(); }; }; - request.send(); + request.send(); + } + + getWeatherData = (appID, cityID, units) => { + + const requestString = `https://api.openweathermap.org/data/2.5/weather?APPID=${appID}&id=${cityID}&units=${units}`; + + this._tempSymbol = (units === 'metric') ? '°C' : '°F'; + + this._fetchOpenWeatherMapDate(requestString, this._processWeatherData); }; @@ -168,17 +177,9 @@ class WeatherScreen { const requestString = `https://api.openweathermap.org/data/2.5/forecast?APPID=${appID}&id=${cityID}&units=${units}`; - const request = new XMLHttpRequest(); - request.open('GET', requestString, true); - request.onload = e => { - if (request.readyState === 4 && request.status === 200 && request.status < 400) { - this._tempSymbol = (units === 'metric') ? '°C' : '°F'; - this._processForecastData(JSON.parse(request.response)); - } else { - this._setErrValue(); - }; - }; - request.send(); + this._tempSymbol = (units === 'metric') ? '°C' : '°F'; + + this._fetchOpenWeatherMapDate(requestString, this._processForecastData); } _processForecastData = data => {