City Fetcher API Challenge
Easy Important
Prompt
In JavaScript, we have two existing APIs that provide state and city data. Your task is to implement a function that fetches and combines data from both APIs to return all cities in a given country.
Requirements
Implement a function getAllCities(country)
that uses the provided APIs (getStates
and getCities
)
to return a promise resolving to an array of all cities in the given country.
Available APIs
getStates(country) → Promise<string[]>
// Returns array of state codesgetCities(state) → Promise<string[]>
// Returns array of cities in state
Playground
Hint
async function getAllCities(country) {
try {
// 1. Get states first
// 2. For each state, how will you get cities?
// 3. How will you combine all the cities?
// 4. Return the final result
} catch (error) {
// How will you handle errors?
}
}
Solution
Code Explanation 💻
Fetch States
- Call
getStates(country)
and await its result - Returns:
['CA', 'NY', 'WA']
Create Promises for Cities
- Map over states array to create an array of promises
- Each promise represents a call to
getCities(state)
- Returns:
[Promise(CA cities), Promise(NY cities), Promise(WA cities)]
Resolve All Promises
- Use
Promise.all()
to wait for all city requests to complete - Returns nested array:
[
['LA', 'SF', 'SD'], // CA cities
['LA1', 'SF1', 'SD1'], // NY cities
['LA2', 'SF2', 'SD2'], // WA cities
];
Flatten Results
- Use
flat()
to combine all cities into a single array - Final result:
['LA', 'SF', 'SD', 'LA1', 'SF1', 'SD1', 'LA2', 'SF2', 'SD2']
Concept Explanation 🧠
Async/Await
- Makes asynchronous code look synchronous
- Improves code readability
- Simplifies error handling with try/catch
Promise.all()
- Executes all city requests in parallel
- More efficient than sequential requests
- Returns array of results in same order as input
Error Handling
- try/catch block catches errors from both APIs
- Properly propagates errors up the chain
Array Methods
map()
: Transforms array of states into array of promisesflat()
: Combines nested arrays into single array
00:00