JAVASCRIPT
Chaining Dependent Asynchronous API Calls
Learn to execute sequential API requests where the output of one call is essential for the next, ensuring data consistency and complex workflow management using async/await.
async function processDependentData(userId) {
try {
// Step 1: Fetch user details
console.log(`Fetching details for user: ${userId}`);
const userResponse = await fetch(`https://api.example.com/users/${userId}`);
if (!userResponse.ok) {
throw new Error(`Failed to fetch user ${userId}. Status: ${userResponse.status}`);
}
const userData = await userResponse.json();
console.log('User Data:', userData);
// Step 2: Use user data (e.g., an organization ID) to fetch related data
if (!userData.organizationId) {
throw new Error('User data does not contain organizationId.');
}
console.log(`Fetching organization data for ID: ${userData.organizationId}`);
const orgResponse = await fetch(`https://api.example.com/organizations/${userData.organizationId}`);
if (!orgResponse.ok) {
throw new Error(`Failed to fetch organization ${userData.organizationId}. Status: ${orgResponse.status}`);
}
const orgData = await orgResponse.json();
console.log('Organization Data:', orgData);
// Step 3: Use both user and organization data to perform another action
const combinedInfo = {
user: userData.name,
organizationName: orgData.name,
organizationType: orgData.type
};
console.log('Combined Information:', combinedInfo);
return combinedInfo;
} catch (error) {
console.error('Error in dependent API call chain:', error.message);
throw error;
}
}
// Example usage:
// processDependentData('user123'); // Replace with a valid user ID
How it works: This snippet demonstrates how to chain multiple API calls sequentially using `async/await`. The output of the first API call (fetching user details) is used as input for the second API call (fetching organization details). This pattern is crucial for workflows where data dependency exists between different API interactions, ensuring operations are performed in the correct order.