const post = async (url, params) => {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(params),
headers: {
'Content-type': 'application/json; charset=UTF-8',
}
})
const data = await response.json()
return data
}
// Then use it like so with async/await:
(async () => {
const data = await post('https://jsonplaceholder.typicode.com/posts', {
title: 'This will be the title',
body: 'Setting the body property',
userId: 1
})
console.log(data)
})()
// Or using then:
post('https://jsonplaceholder.typicode.com/posts', {
title: 'This will be the title',
body: 'Setting the body property',
userId: 1,
}).then(data => console.log(data))
// 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
}
Comments