Master parallel API requests by building a dynamic comparison dashboard that fetches and analyzes data from multiple APIs simultaneously using Promise.all().
By completing this activity, you will:
Master parallel API requests using Promise.all() for concurrent fetching
Handle multiple API response formats and data structures
Build dynamic comparison interfaces with real-time analytics
Implement performance testing and data visualization
Create interactive battle/comparison modes
Optimize API calls with caching and error recovery
IMPORTANT: This template includes WORKING COMPARISON FEATURES! Test them immediately:
Navigate to this folder in your terminal/command prompt
Start a local server (choose one):
bash
python3 -m http.server 8001
python -m http.server 8001
npx http-server -p 8001
Open your browser to: http://localhost:8001
Try the working features :
Select "Pokemon Battle Stats" comparison type
Click "Quick Start: Fire Starters" to load 3 Pokemon instantly
See side-by-side stat comparisons appear
Click "Battle Mode" to see head-to-head comparisons
65% of the code is implemented for you:
Pokemon Comparison - Complete battle stats comparison (attack, defense, speed, HP)
Star Wars Characters - Physical stats and character showdowns
Parallel Fetching - Promise.all() implementation for concurrent API calls
Quick Start Buttons - Pre-loaded examples for instant testing
Responsive Grid Layout - Auto-adjusting card display
Loading States - Animated spinners during API requests
Weather Comparison - Real-time city weather data comparison (TODO 1)
Country Comparison - Population and geographic data analysis (TODO 2)
Performance Analytics - API response time tracking (TODO 3)
Export Functionality - Save comparison data as JSON (TODO 4)
Advanced Battle Mode - Weighted scoring algorithms (Extension)
First: Test the working Pokemon/Star Wars comparisons to understand the pattern
Then: Complete TODO 1 & 2 to add Weather and Country comparison types
Next: Implement TODO 3 & 4 for performance tracking and data export
Finally: Explore extension challenges for advanced features
Attack, Defense, Speed, HP - Core battle stats visualization
Type Effectiveness - Pokemon type combinations
Battle Mode - Head-to-head stat comparisons
Physical Stats - Height, mass, appearance
Character Info - Birth year, homeworld, species
Character Showdown - Physical superiority battles
Temperature - Current and "feels like" comparisons
Weather Conditions - Sky conditions, visibility
Environmental Data - Humidity, pressure, wind speed
Population Data - Current population statistics
Geographic Info - Area, capital cities, regions
Cultural Facts - Languages, currencies, time zones
Complete the Weather API integration to compare real-time weather across cities.
API Endpoint: https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric
Requirements:
Fetch weather data for multiple cities in parallel
Display temperature, conditions, humidity, and wind speed
Show "feels like" temperature comparison
Handle cities not found with helpful error messages
Success Criteria:
Learning Focus: Working with API keys and query parameters
Complete the REST Countries API integration to compare country data.
API Endpoint: https://restcountries.com/v3.1/name/{country}
Requirements:
Fetch country data including population, area, capital
Display flags, languages, and currencies
Calculate population density
Show geographic comparisons
Success Criteria:
Learning Focus: Handling array responses and nested data structures
Implement API response time tracking and comparison analytics.
Requirements:
Track fetch start/end times using performance.now()
Display response times for each API call
Calculate average, min, and max response times
Show performance comparison graph/visualization
Success Criteria:
Learning Focus: Performance monitoring and optimization techniques
Implement JSON export functionality for comparison results.
Requirements:
Create export button that generates JSON download
Include all comparison data and analytics
Format JSON with proper indentation
Generate descriptive filename with timestamp
Success Criteria:
Learning Focus: Data serialization and file downloads with JavaScript
javascript
async function getMultipleItems (itemNames ) {
try {
console .log (`๐ฅ Fetching ${itemNames.length} items simultaneously...` );
const fetchPromises = itemNames.map (name =>
fetch (`${API_BASE} /${name.toLowerCase()} ` )
.then (response => {
if (!response.ok ) throw new Error (`${name} not found` );
return response.json ();
})
);
const itemData = await Promise .all (fetchPromises);
console .log ('โ
All items loaded successfully!' );
return itemData;
} catch (error) {
console .error ('โ Failed to fetch items:' , error);
throw error;
}
}
javascript
async function fetchWithTiming (url ) {
const startTime = performance.now ();
const response = await fetch (url);
const data = await response.json ();
const endTime = performance.now ();
const duration = endTime - startTime;
console .log (`โฑ๏ธ Request took ${duration.toFixed(2 )} ms` );
return { data, duration };
}
javascript
function analyzeComparison (items ) {
const stats = {
count : items.length ,
categories : {}
};
if (comparisonType === 'pokemon' ) {
const attacks = items.map (p => getStatValue (p, 'attack' ));
const defenses = items.map (p => getStatValue (p, 'defense' ));
stats.strongest = {
attacker : items[attacks.indexOf (Math .max (...attacks))],
defender : items[defenses.indexOf (Math .max (...defenses))]
};
}
stats.averages = calculateAverages (items);
return stats;
}
Base URL: https://pokeapi.co/api/v2
Endpoints:
GET /pokemon/{name} - Get Pokemon stats and info
Features: Complete Pokemon database with stats, types, abilities
Rate Limit: No official limit (be respectful with requests)
CORS: Enabled for browser requests
Documentation: pokeapi.co/docs
Example Response:
json
{
"name" : "pikachu" ,
"stats" : [
{ "stat" : { "name" : "hp" } , "base_stat" : 35 } ,
{ "stat" : { "name" : "attack" } , "base_stat" : 55 }
] ,
"types" : [ { "type" : { "name" : "electric" } } ]
}
Base URL: https://swapi.tech/api (Updated: Original swapi.dev is no longer available)
Endpoints:
GET /people/{id}/ - Get character information
Features: Characters, vehicles, planets from Star Wars universe
Rate Limit: No official limit
CORS: Enabled for browser requests
Documentation: swapi.tech
Example Response:
json
{
"name" : "Luke Skywalker" ,
"height" : "172" ,
"mass" : "77" ,
"birth_year" : "19BBY" ,
"homeworld" : "https://swapi.dev/api/planets/1/"
}
Base URL: https://api.openweathermap.org/data/2.5
Endpoints:
GET /weather?q={city}&appid={API_KEY}&units=metric
Features: Real-time weather data for cities worldwide
Rate Limit: 1000 calls/day (free tier)
CORS: Enabled
Get API Key: Sign up here (free)
Documentation: openweathermap.org/api
Example Response:
json
{
"main" : {
"temp" : 15.5 ,
"feels_like" : 14.2 ,
"humidity" : 72
} ,
"weather" : [ { "description" : "light rain" } ] ,
"wind" : { "speed" : 4.5 }
}
Base URL: https://restcountries.com/v3.1
Endpoints:
GET /name/{country} - Search by country name
Features: Comprehensive country data including demographics
Rate Limit: No official limit
CORS: Enabled for browser requests
Documentation: restcountries.com
Example Response:
json
[ {
"name" : { "common" : "Japan" } ,
"population" : 125584838 ,
"area" : 377930 ,
"capital" : [ "Tokyo" ] ,
"flags" : { "png" : "https://..." }
} ]
Working Features (Test These First):
TODO Features (Test After Implementation):
Test One: Parallel Loading Speed
Select Pokemon comparison
Click "Quick Start: Fire Starters"
Open DevTools Network tab
Verify all 3 requests start simultaneously (not sequential)
Check total time is ~1 API call, not 3x
Test 2: Error Handling
Try fetching non-existent Pokemon ("asdfghjkl")
Verify error message displays clearly
Other comparison items should remain intact
Application should not crash
Test 3: API Response Time Comparison (after TODO 3)
Load Pokemon (fast API)
Load Weather data (medium speed API)
Compare response times in performance panel
Verify timing accuracy within 50ms
Using Browser DevTools:
Console Tab - View API calls and timing logs
Network Tab - Inspect API requests/responses
Elements Tab - Check DOM updates and styling
Performance Tab - Monitor fetch timing and rendering
Common Issues & Solutions:
Issue: Promise.all() fails if one item is invalid
Solution: Use Promise.allSettled() instead to handle partial failures
Issue: Weather API returns 401 Unauthorized
Solution: Check API key is correctly set in script.js
Issue: Country API returns array, not object
Solution: Access first element with data[0] for country data
Issue: Performance timing shows NaN
Solution: Ensure performance.now() is called before and after fetch
One. Add More Quick Start Options
Create additional quick start button sets
Pokemon: Water starters (Squirtle, Wartortle, Blastoise)
Star Wars: Droids (R2-D2, C-3PO, BB-8)
Success Criteria: Buttons load 3 items in parallel
2. Favorite Comparison Items
Add star icon to each comparison card
Save favorites to localStorage
Display favorites list in sidebar
Success Criteria: Favorites persist across page refreshes
3. Comparison History Tracking
Log each comparison to localStorage
Show "Recent Comparisons" section
One-click reload of previous comparisons
Success Criteria: Last 5 comparisons saved and retrievable
One. Data Visualization Charts
Add Chart.js library for visualizations
Create bar chart comparing numeric stats
Radar chart for multi-dimensional comparisons
Success Criteria: Charts update dynamically as items added/removed
2. Advanced Battle Scoring
Implement weighted scoring algorithm
User-configurable stat weights (attack 40%, defense 30%, etc.)
Show breakdown of score calculation
Success Criteria: Battle winner changes based on weight adjustments
3. Multi-API Mashups
Combine Pokemon + Weather: "Best weather for Pokemon type"
Combine Countries + Star Wars: "Which character's homeworld matches this country?"
Success Criteria: Creative data relationships displayed meaningfully
4. Caching & Offline Support
Implement localStorage cache for API responses
Cache timeout of 5 minutes
Offline mode with cached data
Success Criteria: Second load of same item is instant (cached)
One. Real-Time Collaborative Comparisons
Use Firebase Realtime Database
Share comparison room with unique URL
Multiple users add items simultaneously
Success Criteria: Changes visible across all connected clients
2. API Rate Limiting & Queue Management
Implement request queue for rate-limited APIs
Show queue position and estimated wait time
Throttle requests to stay under limits
Success Criteria: Never exceed API rate limits, graceful queuing
3. Machine Learning Predictions
Use TensorFlow.js for battle outcome predictions
Train model on historical battle data
Show confidence percentage for predictions
Success Criteria: Prediction ``accuracy > 70``% after training
4. Custom API Integration
Add configuration panel for custom APIs
User inputs: API URL, response mapping, display fields
Save custom configurations to localStorage
Success Criteria: User can add their own API without coding
Caching Strategies - localStorage, sessionStorage, Cache API
Error Recovery - Retry logic, fallback data, graceful degradation
Data Visualization - Chart.js, D3.js for graphs
Performance Optimization - Debouncing, throttling, lazy loading
Your project is complete when:
โ
All 4 TODO functions are implemented
โ
Pokemon and Star Wars comparisons work perfectly
โ
Weather and Country APIs fetch and display correctly
โ
Performance timing tracks all API calls accurately
โ
Export functionality generates valid JSON downloads
โ
Battle mode works across all comparison types
โ
Loading states and error handling are graceful
โ
Project works on both desktop and mobile
โ
Code is clean with proper comments
โ
All manual tests pass successfully
Once you complete this project, you'll have mastered:
Parallel API Requests with Promise.all() for optimal performance
Multiple API Integration handling diverse response formats
Performance Monitoring tracking and optimizing API call timing
Data Comparison Logic building analytics and battle systems
Error Handling managing failures across concurrent requests
Data Export serializing and downloading JSON data
This advanced activity showcases your ability to work with multiple APIs simultaneously-a critical skill for building modern web applications that aggregate data from various sources.
graphql
activity-06 -comparison/
โโโ index.html
โโโ styles.css
โโโ script.js
โโโ sample-data.json
โโโ README.md
Need Help?
Check the browser console for API call logs and timing data
Review the TODO comments in script.js for implementation guidance
Test working features (Pokemon, Star Wars) to understand patterns
Use Network tab to inspect API requests/responses
Verify API keys are correctly configured (Weather API)
Compare your implementation with working comparison types
Happy coding! Build amazing comparison dashboards! ๐โจ