Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Last active April 2, 2019 20:15
Show Gist options
  • Save gladchinda/e8bfe1d450d3d0f95966519828af7e2c to your computer and use it in GitHub Desktop.
Save gladchinda/e8bfe1d450d3d0f95966519828af7e2c to your computer and use it in GitHub Desktop.
// Use your OpenWeatherMap API KEY
// Set the current weather data API URL
const API_KEY = 'YOUR_API_KEY_HERE';
const API_URL = `https://api.openweathermap.org/data/2.5/weather?appid=${API_KEY}&units=metric`;
// Set the list of cities
const CITIES = [
'London', 'Tokyo', 'Melbourne', 'Vancouver',
'Lagos', 'Berlin', 'Paris', 'Johannesburg',
'Chicago', 'Mumbai', 'Cairo', 'Beijing'
];
/**
* Fetches the current temperature of a city (in °C).
* @param {string} city The city to fetch its current temperature
* @returns {Promise} A promise that is fulfilled with an array of the format [city, temp]
*/
const fetchTempForCity = city => {
// Append the encoded city name to the API URL and make a request with `fetch()`
// From the JSON response, get the value of the `main.temp` property
// Return a promise that is fulfilled with an array of the format [city, temp]
// For example: ['Lagos', 29.28]
return fetch(`${API_URL}&q=${encodeURIComponent(city)}`)
.then(response => response.json())
.then(data => [ city, data.main.temp || null ]);
}
/**
* Fetches the current temperatures of multiple cities (in °C).
* @param {Array} cities The cities to fetch their current temperatures
* @returns {Promise} A promise that is fulfilled with an object map of each city against temp
*/
const fetchTempForCities = cities => {
// Use `Array.prototype.map()` to create a Promise for each city's current temperature.
// Use `Promise.all()` to execute all the promises in parallel (as a single batch).
// When all the promises have been settled, use `Array.prototype.reduce()` to construct
// an object map of each city in the list of cities against its current temperature (in °C).
// Return a promise that is fulfilled with the object map
return Promise.all(cities.map(fetchTempForCity))
.then(temps => {
return temps.reduce((data, [ city, temp ]) => {
return { ...data, [city]: Number.isFinite(temp) ? temp.toFixed(2) * 1 : null };
}, {});
});
}
// Fetch the current temperatures for all the cities listed in CITIES
// `console.log()` the data on fulfillment and `console.error()` on rejection
fetchTempForCities(CITIES)
.then(console.log, console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment