Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <title>Promise.all Example</title>
- </head>
- <body>
- <button id="fetchBtn">Fetch Data</button>
- <div id="output">Click the button to load data...</div>
- <script>
- const btn = document.getElementById('fetchBtn');
- const output = document.getElementById('output');
- // The function triggered by the event
- async function handleLoadData() {
- output.innerHTML = "Loading...";
- // Define the API endpoints
- const userUrl = 'https://jsonplaceholder.typicode.com/users/1';
- const postsUrl = 'https://jsonplaceholder.typicode.com/posts?userId=1';
- try {
- // 1. Start both fetches at the same time
- // Promise.all wraps them into a single promise
- const [userResponse, postsResponse] = await Promise.all([
- fetch(userUrl),
- fetch(postsUrl)
- ]);
- // 2. Parse both responses as JSON in parallel
- const [userData, postsData] = await Promise.all([
- userResponse.json(),
- postsResponse.json()
- ]);
- // 3. Update the UI with both sets of data
- output.innerHTML = `
- <h3>User: ${userData.name}</h3>
- <p>Email: ${userData.email}</p>
- <h4>Recent Posts:</h4>
- <ul>
- ${postsData.map(post => `<li>${post.title}</li>`).join('')}
- </ul>
- `;
- } catch (error) {
- // If ANY of the requests fail, it will land here
- output.innerHTML = "Error loading data: " + error.message;
- console.error("Request failed", error);
- }
- }
- // Single Event Listener
- btn.addEventListener('click', handleLoadData);
- </script>
- </body>
- </html>
Advertisement