Last active
April 3, 2019 10:39
-
-
Save gladchinda/ef971dfa6d80ce9ea5d20393e8ec5973 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An object that will contain the current temperatures of the cities | |
// The keys are the city names, while the values are their current temperatures (in °C) | |
let TEMPS = null; | |
// The maximum number of retries for failed temperature fetches | |
const MAX_TEMP_FETCH_RETRIES = 5; | |
/** | |
* Fetches the current temperatures of multiple cities (in °C) and update the `TEMPS` object. | |
* Also schedule retries for failed temperature fetches. | |
* @param {Array} cities The cities to fetch their current temperatures | |
* @param {number} retries The current number of retries so far | |
* @returns {Promise} A promise that is fulfilled with the updated `TEMPS` object. | |
*/ | |
const fetchTemperatures = (cities, retries = 0) => { | |
return fetchTempForCities(cities) | |
.then(temps => { | |
// Update the `TEMPS` object with updated city temperatures from `temps` | |
TEMPS = (TEMPS === null) ? temps : { ...TEMPS, ...temps }; | |
// Filter the keys (cities) of the `TEMPS` object to get a list of the cities | |
// with `null` temperature values. | |
const RETRY_CITIES = Object.keys(TEMPS) | |
.filter(city => TEMPS[city] == null); | |
// If there are 1 or more cities in the `RETRY_CITIES` list | |
// and the maximum retries has not been exceeded, | |
// attempt to fetch their temperatures again after waiting for 5 seconds. | |
// Also increment `retries` by 1. | |
if (RETRY_CITIES.length > 0 && retries < MAX_TEMP_FETCH_RETRIES) { | |
setTimeout(() => fetchTemperatures(RETRY_CITIES, ++retries), 5 * 1000); | |
} | |
// Return the updated `TEMPS` object | |
return TEMPS; | |
}) | |
.then(console.log, console.error); | |
} | |
// Fetch the current temperatures of the cities in the `CITIES` list | |
// and update the `TEMPS` object | |
fetchTemperatures(CITIES); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment