Skip to content

Node.js – Async Code

Rules

  • Always use async/await — avoid raw Promise chains and callbacks
  • Every await must be inside a try/catch or centralized error handler
  • Never use async functions inside forEach
  • Use Promise.all() for independent parallel operations
  • Always set timeouts on external HTTP calls

forEach vs for...of

// Correct
for (const item of items) {
  await processItem(item);
}

// Incorrect — errors silently swallowed
items.forEach(async (item) => {
  await processItem(item);
});

Parallel Operations

// Correct — runs both at the same time
const [user, orders] = await Promise.all([
  getUser(userId),
  getOrders(userId)
]);

// Incorrect — sequential, slower
const user = await getUser(userId);
const orders = await getOrders(userId);