Async/Await Data Fetcher
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
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.
Codeasync 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
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.
Codeasync 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
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.
Codeasync 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
Write a retry wrapper
Create an async function withRetry(fn, retries, delay) that calls fn, and on rejection waits and retries up to
retriestimes with exponential backoff.Codeasync 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
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.
Codelet 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
async function fetchUserData(id) { /* TODO */ }
async function withRetry(fn, retries, delay) { /* TODO */ }async function withRetry(fn, r = 3, d = 100) { for (let a = 0; a <= r; a++) { try { return await fn(); } catch (e) { if (a === r) throw e; await new Promise(x => setTimeout(x, d * 2**a)); } } }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
- Async/Await
Modern async syntax.
- Promises
Promise.all for concurrent fetches.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.