const util = require('util');
const fs = require('fs');
// Convert callbacks to promises
const readFile = util.promisify(fs.readFile);
// Function with a nested chain of async operations
async function processUserData(userId) {
try {
console.log(`Processing data for user ${userId}...`);
// Fetch user data
const userData = await fetchUserData(userId);
console.log(`User data retrieved: ${userData.name}`);
// Get user posts
const posts = await getUserPosts(userId);
console.log(`Retrieved ${posts.length} posts for user`);
// Process posts (this will cause an error for userId = 3)
const processedPosts = posts.map(post => {
return {
id: post.id,
title: post.title.toUpperCase(),
contentLength: post.content.length, // Will fail if content is undefined
};
});
return { user: userData, posts: processedPosts };
} catch (error) {
console.error('Error processing user data:', error);
throw error;
}
}
// Simulated API call
function fetchUserData(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId <= 0) {
reject(new Error('Invalid user ID'));
} else {
resolve({ id: userId, name: `User ${userId}` });
}
}, 500);
});
}
// Simulated database query
function getUserPosts(userId) {
return new Promise((resolve) => {
setTimeout(() => {
// Bug: post with undefined content for userId 3
if (userId === 3) {
resolve([
{ id: 1, title: 'First Post', content: 'Content' },
{ id: 2, title: 'Second Post', content: undefined }
]);
} else {
resolve([
{ id: 1, title: 'First Post', content: 'Content' },
{ id: 2, title: 'Second Post', content: 'More content' }
]);
}
}, 300);
});
}
// Usage
processUserData(3).catch(err => console.log('Caught at top level:', err.message));