JAVASCRIPT
Executing Parallel and Sequential Dependent API Calls
Master fetching data from multiple API endpoints by executing requests in parallel using `Promise.all` and sequentially with `async/await` for dependent operations.
async function fetchUserData(userId) {
console.log(`Fetching user ${userId}...`);
const response = await fetch(`https://api.example.com/users/${userId}`);
if (!response.ok) throw new Error(`Failed to fetch user ${userId}`);
return response.json();
}
async function fetchUserPosts(userId) {
console.log(`Fetching posts for user ${userId}...`);
const response = await fetch(`https://api.example.com/users/${userId}/posts`);
if (!response.ok) throw new Error(`Failed to fetch posts for user ${userId}`);
return response.json();
}
async function fetchPostComments(postId) {
console.log(`Fetching comments for post ${postId}...`);
const response = await fetch(`https://api.example.com/posts/${postId}/comments`);
if (!response.ok) throw new Error(`Failed to fetch comments for post ${postId}`);
return response.json();
}
// --- Scenario 1: Parallel API Calls (Independent) ---
async function fetchDashboardData(userId) {
try {
console.log('--- Parallel Fetch for Dashboard ---');
const [userData, userPosts] = await Promise.all([
fetchUserData(userId),
fetchUserPosts(userId)
]);
console.log('Dashboard Data (Parallel):', { userData, userPosts });
return { userData, userPosts };
} catch (error) {
console.error('Error fetching dashboard data:', error);
}
}
// --- Scenario 2: Sequential Dependent API Calls ---
async function fetchUserActivityDetails(userId) {
try {
console.log('--- Sequential Fetch for User Activity ---');
const userData = await fetchUserData(userId); // First, get user data
console.log('Fetched user data:', userData);
// Now, use data from the first call to make the second call
if (userData && userData.latestPostId) {
const comments = await fetchPostComments(userData.latestPostId);
console.log('User Activity Details (Sequential):', { userData, latestPostComments: comments });
return { userData, latestPostComments: comments };
} else {
console.log('User has no latest post or post ID missing.');
return { userData };
}
} catch (error) {
console.error('Error fetching user activity details:', error);
}
}
// Example calls:
const sampleUserId = 123;
fetchDashboardData(sampleUserId);
// Simulate some latency for the sequential call
setTimeout(() => fetchUserActivityDetails(sampleUserId), 100);
How it works: This JavaScript snippet illustrates two common patterns for orchestrating multiple API requests. The first scenario demonstrates **parallel fetching** using `Promise.all()`, where independent API calls are initiated concurrently to retrieve data more quickly (e.g., user profile and their posts for a dashboard). The second scenario shows **sequential fetching** using `async/await`, where subsequent API calls depend on the results of previous ones (e.g., fetching user details, then using a `postId` from those details to fetch comments for that specific post). This approach ensures data consistency and efficient loading based on interdependencies.