Promise Chaining & Error Handling

Promise Chaining Fundamentals

Promise chaining allows you to execute asynchronous operations in sequence, where each operation starts when the previous one completes.

Key Rule: A .then() handler can return:
  • A value (which becomes the resolved value)
  • Another promise (waits for it to settle)
  • A thrown error (which becomes a rejected promise)

Example 1: Basic Promise Chaining

JavaScript Editor
✅ What You Can Return in .then()
  • Primitive values: return 42;
  • Objects: return {data: 'value'};
  • Another Promise: return fetch(url);
  • Nothing: return; (returns undefined)
  • Error: throw new Error('msg');
⚠️ Common Mistakes
  • Forgetting to return from .then()
  • Not handling errors properly
  • Creating promise pyramids (like callback hell)
  • Mixing async/await with .then() unnecessarily
  • Not cleaning up resources in finally()

Example 2: Different Return Types

JavaScript Editor
🔥 Error Handling Patterns
1. Global Catch
promise
  .then(step1)
  .then(step2)
  .then(step3)
  .catch(handleAllErrors)
2. Recovery After Error
promise
  .then(step1)
  .catch(error => {
    // Recover
    return defaultValue;
  })
  .then(continue)
3. Rethrow Error
promise
  .then(step1)
  .catch(error => {
    // Log and rethrow
    console.error(error);
    throw error;
  })
  .then(step2)

Example 3: Error Handling in Chains

JavaScript Editor

Example 4: Parallel vs Sequential Execution

JavaScript Editor
📊 Promise.all() vs Promise.allSettled() vs Promise.race()
MethodBehaviorUse CaseResult
Promise.all()All must succeedWhen all promises are neededRejects if ANY fails
Promise.allSettled()Wait for all to completeWhen you need all results regardlessNever rejects
Promise.race()First to settle winsTimeout patterns, fastest responseFirst settled (resolved/rejected)
Promise.any()First to succeed winsMultiple fallback sourcesFirst resolved, rejects if ALL fail

Example 5: Advanced Chain Patterns

JavaScript Editor
Exercise: Implement Promise Chain
JavaScript Editor
💡 Best Practices for Promise Chaining
  • Always return promises from async functions
  • Use async/await for complex chains
  • Handle errors at appropriate levels
  • Use Promise.all() for parallel independent operations
  • Avoid nesting promises (anti-pattern)
  • Clean up resources in finally()