Skip to content

Async/Await Data Fetcher

Medium ~35 min

What you'll build

An async fetcher with a retry-with-backoff wrapper, concurrent fetching via Promise.all, and clean error handling using try/catch.

Goals

  • Use async/await for sequential async code
  • Handle errors with try/catch
  • Run concurrent fetches with Promise.all + await
  • Implement a retry wrapper with exponential backoff

Prerequisites

  • Promise chains (from project-11)
  • try/catch error handling
  • async/await syntax

Steps

  1. 1

    Write an async fetcher

    Create an async function that uses await to call three APIs in sequence. await unwraps the Promise so you can write async code that reads like sync code.

    Code
    async function fetchUserData(userId) {
      const user = await getUser(userId);
      const posts = await getPosts(user.id);
      return { user, posts };
    }

    Expected result

    Calling fetchUserData(1) returns a Promise that resolves with { user, posts }.

  2. 2

    Add try/catch error handling

    Wrap the awaits in try/catch. If any await rejects, control jumps to catch. Log the error and return a fallback value.

    Code
    async function fetchUserData(userId) {
      try {
        const user = await getUser(userId);
        const posts = await getPosts(user.id);
        return { user, posts };
      } catch (err) {
        console.error('Fetch failed:', err);
        return { user: null, posts: [] };
      }
    }

    Expected result

    If getUser rejects, the function returns the fallback instead of throwing.

  3. 3

    Fetch concurrently with Promise.all

    If you need multiple independent pieces of data, await Promise.all([...]) to fetch them concurrently rather than one at a time.

    Code
    async function fetchDashboard(userId) {
      const [profile, notifications, settings] = await Promise.all([
        getProfile(userId),
        getNotifications(userId),
        getSettings(userId),
      ]);
      return { profile, notifications, settings };
    }

    Expected result

    All three fetches run in parallel; total time is the slowest, not the sum.

  4. 4

    Write a retry wrapper

    Create an async function withRetry(fn, retries, delay) that calls fn, and on rejection waits and retries up to retries times with exponential backoff.

    Code
    async function withRetry(fn, retries = 3, delay = 100) {
      for (let attempt = 0; attempt <= retries; attempt++) {
        try {
          return await fn();
        } catch (err) {
          if (attempt === retries) throw err;
          const wait = delay * Math.pow(2, attempt);
          console.log(`Retry ${attempt + 1} in ${wait}ms`);
          await new Promise(r => setTimeout(r, wait));
        }
      }
    }

    Expected result

    withRetry(() => flakyApi(), 3) retries up to 3 times with 100, 200, 400ms waits.

  5. 5

    Combine and test

    Use withRetry to wrap a flaky API call inside fetchUserData. Test with an API that fails 50% of the time to confirm retries work.

    Code
    let calls = 0;
    async function flakyApi() {
      calls++;
      if (Math.random() < 0.5) throw new Error('Random fail');
      return 'success on call ' + calls;
    }
    
    (async () => {
      const result = await withRetry(flakyApi, 3);
      console.log('Result:', result, 'after', calls, 'calls');
    })();

    Expected result

    Eventually succeeds, logging the result and number of calls (1-4).

Try it yourself

What you learned

You mastered async/await — the modern way to write async JS — and built a production-grade retry wrapper with exponential backoff, used in real fetch libraries.

Related Resources

Related Lessons

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