// Function to fetch weather data from an API
const fetchWeather = () => {
return fetch('https://api.example.com/weather')
.then((response) => {
if (!response.ok) {
throw new Error('Failed to fetch weather data');
}
return response.json();
})
.then((data) => {
return { temperature: data.temperature, condition: data.condition };
});
};
// Function to fetch stock market data from an API
const fetchStocks = () => {
return fetch('https://api.example.com/stocks')
.then((response) => {
if (!response.ok) {
throw new Error('Failed to fetch stock data');
}
return response.json();
})
.then((data) => {
return { symbol: data.symbol, price: data.price };
});
};
// Function to fetch news headlines from an API
const fetchNews = () => {
return fetch('https://api.example.com/news')
.then((response) => {
if (!response.ok) {
throw new Error('Failed to fetch news data');
}
return response.json();
})
.then((data) => {
return data.articles.map(article => ({ title: article.title }));
});
};
// Fetch all data in parallel using Promise.all
Promise.all([fetchWeather(), fetchStocks(), fetchNews()])
.then(([weatherData, stockData, newsData]) => {
console.log('Weather:', weatherData);
console.log('Stocks:', stockData);
console.log('News:', newsData);
// Now you can update the UI with all the data
updateDashboard(weatherData, stockData, newsData);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
// Example of how you could update the dashboard
function updateDashboard(weather, stocks, news) {
console.log('Updating dashboard with all the data...');
// Logic to update the UI with the fetched data
}