⚡
Weather App with API 🌤️
Advanced
170 XP
75 min
Lesson Content
Weather App with API 🌤️
Build a weather app that fetches real data from an API. This teaches you async JavaScript and API integration!
Fetch API
async function getWeather(city) {
try {
const response = await fetch(`https://api.weather.com/${city}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}Error Handling
async function fetchWithErrorHandling(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error('API error');
return await response.json();
} catch (error) {
console.error('Failed:', error.message);
}
}Example Code
Practice fetching data from API
// Simulate API call
async function getWeather(city) {
// In real app, this would fetch from API
return new Promise(resolve => {
setTimeout(() => {
resolve({ city, temp: 22, condition: 'Sunny' });
}, 1000);
});
}
async function displayWeather() {
const weather = await getWeather('London');
console.log(`${weather.city}: ${weather.temp}°C, ${weather.condition}`);
}
displayWeather();Expected Output:
Weather data displayed
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code