030
LVL 01 — WAVE DEFENDER SESSION 030 DAY 30

ASYNC / AWAIT

🎫 PIXELCRAFT-018
🔧 Refactor | 🟡 Medium | Priority: 🟡 Medium

The upload → resize → filter → export flow is 5 callbacks deep. Unreadable. Refactor using Promises and async/await.
CONCEPTS.UNLOCKED
🤝
Promises
Representing a future value: pending → fulfilled or rejected. A Promise is an object that says "I don't have the result yet, but I will — and you can attach handlers for when I do."
.then
.then() / .catch() / .finally()
.then(onSuccess) — runs when fulfilled. .catch(onError) — runs when rejected. .finally() — runs either way. Clean separation of success and error paths.
🔗
Promise Chaining
loadFile().then(decode).then(filter).then(export) — each .then() returns a new Promise. Flat, readable, no nesting. Each step's output feeds into the next.
async / await
Syntactic sugar that makes async code look synchronous. const data = await readFile(file) — pauses execution until the Promise resolves. Same behavior, dramatically better readability.
Promise.all()
Run multiple operations in parallel: Promise.all([task1, task2, task3]). All run simultaneously. Resolves when ALL complete. Rejects if ANY fails.
📐
Creating Promises
new Promise((resolve, reject) => { ... }) — wrap callback-based APIs in Promises. Call resolve(value) on success, reject(error) on failure. The bridge from old patterns to new.
HANDS-ON.TASKS
01
See the Callback Hell
readFile(file, function(data) { decodeImage(data, function(img) { resizeImage(img, maxWidth, function(resized) { applyFilter(resized, 'grayscale', function(filtered) { exportImage(filtered, 'output.png', function(result) { console.log("Done!", result); }); }); }); }); });
5 levels of nesting. Each step depends on the previous one. The "pyramid of doom" — where error handling, readability, and maintainability go to die.
02
Convert Steps to Promises
function readFilePromise(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = () => reject(new Error('Failed to read file')); reader.readAsDataURL(file); }); }
new Promise() wraps the callback-based FileReader API. resolve() fires .then(), reject() fires .catch(). The callback is hidden inside — the outside world sees a clean Promise.
03
Chain with .then()
readFilePromise(file) .then(data => decodeImage(data)) .then(img => resizeImage(img, maxWidth)) .then(resized => applyFilter(resized, 'grayscale')) .then(filtered => exportImage(filtered, 'output.png')) .then(result => console.log("Done!", result)) .catch(error => showToast(error.message, 'error'));

Flat, readable, one .catch() handles errors from any step. Compare this to the 5-level nested version above.

04
Rewrite with async/await
async function processImage(file) { try { const data = await readFilePromise(file); const img = await decodeImage(data); const resized = await resizeImage(img, maxWidth); const filtered = await applyFilter(resized, 'grayscale'); const result = await exportImage(filtered, 'output.png'); console.log("Done!", result); } catch (error) { showToast(error.message, 'error'); } }
Reads like a recipe: step 1, step 2, step 3. Each await pauses until the Promise resolves, then continues. The async keyword marks the function as returning a Promise.
05
Parallel Processing with Promise.all()
const results = await Promise.all([ processImage(file1), processImage(file2), processImage(file3), ]);

All 3 images process simultaneously. If sequential processing takes 3 seconds, parallel takes ~1 second. Massive performance win for batch operations.

06
Close the Ticket
git switch -c refactor/PIXELCRAFT-018-async-await git add src/scripts/ git commit -m "Refactor callback hell to async/await (PIXELCRAFT-018)" git push origin refactor/PIXELCRAFT-018-async-await # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Promises/Futures exist in almost every modern language.

The concept is universal: represent a value that doesn't exist yet.

// The same concept across languages:

JavaScript  → Promise + async/await
Java        → CompletableFuture
Python      → asyncio
Rust        → Future
C#          → Task
Swift       → async/await

// Essential for: network requests,
// database queries, file I/O — any
// operation that takes time.

// async/await is syntactic sugar that makes
// asynchronous code read like synchronous
// code, dramatically improving readability.
"Async Mastery"
[A] Create a sleep(ms) function that returns a Promise: const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); Use it to simulate a slow upload with a loading animation.
[B] Use Promise.allSettled() to process 5 images where some might fail. Show results for successful ones and error messages for failed ones — don't let one failure kill the batch.
[C] Build a "batch export" feature: upload multiple files → process all in parallel with Promise.all() → export each with a numbered filename. Show total processing time.
REF.MATERIAL
ARTICLE
Mozilla Developer Network
Complete Promise reference: constructor, then/catch/finally, static methods (all, allSettled, race, any), and chaining patterns.
PROMISESMDNREFERENCE
VIDEO
Web Dev Simplified
Clear walkthrough of Promises: creating, chaining, error handling, and the transition from callbacks to then() to async/await.
PROMISESPRACTICAL
VIDEO
Fireship
Rapid overview of async/await: syntax, error handling with try/catch, and common patterns. Watch after understanding Promises.
ASYNC/AWAITQUICK
ARTICLE
javascript.info
In-depth async/await tutorial: converting Promises, error handling, parallel execution, and common pitfalls. Interactive examples.
ASYNC/AWAITINTERACTIVE
ARTICLE
javascript.info
Promise fundamentals from scratch: the executor, resolve/reject, then/catch, chaining, and error propagation. Start here if Promises feel abstract.
PROMISESFUNDAMENTALS
// LEAVE EXCITED BECAUSE
5 levels of nesting became flat, readable code. async/await feels like magic — asynchronous code that reads like a normal recipe. You tamed the callback beast.
🎓 INTERN REVIEW — SESSION 30 MILESTONE

You've completed 18 tickets covering:

HTML: document structure, semantic elements, meta tags, forms, accessibility

CSS: selectors, box model, flexbox, grid, animations, responsive design, variables, specificity

JavaScript: variables, conditionals, loops, functions, objects, arrays, DOM, events, Canvas, error handling, strings, localStorage, higher-order functions, event loop, Promises, async/await

Workflow: terminal, Git (branch/commit/push/PR/merge), ticket lifecycle, code review

You navigate the terminal, use Git professionally, follow the ticket workflow, and write clean, non-duplicated code.

🟣 PROMOTION TO JUNIOR DEVELOPER!