Skip to content

Promise Chain Workflow

Medium ~35 min

What you'll build

A simulated data pipeline that chains three async steps using Promises, with error handling and parallel enrichment via Promise.all.

Goals

  • Chain promises with then for sequential async steps
  • Handle errors with catch and clean up with finally
  • Use Promise.all to run independent steps in parallel
  • Transform data through a pipeline of async functions

Prerequisites

  • Functions and callbacks
  • Array methods (map, flatMap)
  • Promise concept (pending, fulfilled, rejected)

Steps

  1. 1

    Create mock async APIs

    Build three functions that return Promises resolving after a delay: getUser(id), getPosts(userId), getComments(postId). Use setTimeout to simulate network latency.

    Code
    function delay(ms, value) {
      return new Promise(resolve => setTimeout(() => resolve(value), ms));
    }
    
    function getUser(id) {
      return delay(100, { id, name: 'User ' + id });
    }
    function getPosts(userId) {
      return delay(150, [{ id: 1, userId, title: 'Post A' }, { id: 2, userId, title: 'Post B' }]);
    }
    function getComments(postId) {
      return delay(100, [{ postId, text: 'Great!' }, { postId, text: 'Thanks' }]);
    }

    Expected result

    Each function returns a Promise that resolves with mock data after a delay.

  2. 2

    Chain user → posts

    Use .then to first get the user, then their posts. Each then receives the previous result and returns the next Promise, forming a chain.

    Code
    getUser(1)
      .then(user => {
        console.log('User:', user);
        return getPosts(user.id);
      })
      .then(posts => console.log('Posts:', posts));

    Expected result

    After ~250ms, logs the user then their posts.

  3. 3

    Enrich posts with comments in parallel

    For each post, fetch comments. Since the posts are independent, use Promise.all to fetch all comments in parallel rather than sequentially.

    Code
    getUser(1)
      .then(user => getPosts(user.id).then(posts => ({ user, posts })))
      .then(({ user, posts }) => {
        return Promise.all(
          posts.map(post => getComments(post.id).then(comments => ({ ...post, comments })))
        ).then(enrichedPosts => ({ user, posts: enrichedPosts }));
      })
      .then(result => console.log('Enriched:', result));

    Expected result

    Each post now includes a comments array, fetched in parallel.

  4. 4

    Add error handling

    Append .catch to handle any rejection in the chain, and .finally to log that the pipeline completed regardless of outcome.

    Code
      .catch(err => console.error('Pipeline failed:', err))
      .finally(() => console.log('Pipeline done'));

    Expected result

    If any step rejects, the error is logged; 'Pipeline done' always logs.

  5. 5

    Test the full pipeline

    Run the complete chain and verify the final result shape: { user, posts: [{ id, userId, title, comments }] }. Time it to confirm parallel fetching is faster than sequential.

    Code
    const start = Date.now();
    // ... full chain ...
    // Inside final .then:
    console.log('Took', Date.now() - start, 'ms');
    // Sequential would be ~100+150+100+100 = 450ms
    // Parallel comments: ~100+150+100 = 350ms

    Expected result

    Pipeline completes in ~350ms (parallel) rather than ~450ms (sequential).

Try it yourself

What you learned

You built a real async data pipeline with sequential and parallel steps — Promise chains are the foundation of fetch-based data loading in every web app.

Related Resources

Related Lessons

  • Promises

    then, catch, finally, and Promise.all.

  • Async/Await

    The modern syntax for the same pattern.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic