1. Synchronous vs asynchronous

JavaScript is single-threaded โ€” it can only do one thing at a time. In synchronous code, each line waits for the previous one to finish before running. If one task takes 5 seconds, everything after it is blocked.

๐Ÿฝ๏ธ
Restaurant Analogy
How a waiter handles orders

Synchronous waiter: Takes an order, walks to the kitchen, stands there watching the chef cook, waits until the dish is done, brings it to the table, then goes to the next table. One customer at a time โ€” the rest starve.

Asynchronous waiter: Takes an order, hands it to the kitchen, and immediately walks to the next table. When the kitchen rings the bell, the waiter picks up the dish and delivers it. Multiple orders in progress at once.

JavaScript's async model works exactly like the smart waiter. It hands off slow tasks (network requests, timers, file reads) and keeps running the rest of your code.

๐Ÿšซ

Synchronous (blocking)

Each line waits for the previous one. Slow tasks freeze the entire page. Users see a blank screen.

โšก

Asynchronous (non-blocking)

Slow tasks run in the background. JS keeps executing other code. The page stays responsive.

sync-vs-async.js The difference in action
Key insight: In the async version, line 3 prints before line 2 finishes. The setTimeout schedules the callback for later, and JavaScript moves on immediately. This is the foundation of everything async.

2. setTimeout & setInterval

The simplest async functions in JavaScript are setTimeout (run once after a delay) and setInterval (run repeatedly at an interval). They're your first taste of async behavior.

timeout.js setTimeout โ€” run once after delay
๐Ÿ”ฅ
UrbanCart Example
Flash sale countdown

UrbanCart runs a flash sale that ends in 10 seconds. We use setInterval to tick the countdown every second and clearInterval to stop it when time runs out.

countdown.js setInterval โ€” flash sale timer
Always clear intervals: If you forget clearInterval(), the timer runs forever โ€” eating memory and potentially causing bugs. Always store the interval ID and clear it when done.

3. Callbacks

A callback is a function you pass to another function, which calls it back when the async work is done. This is how JavaScript handled async code before Promises existed.

callback.js The callback pattern
Callback flow
Call fetchProducts(callback)
โ†’
setTimeout starts (1.5s)
โ†’
Timer fires, calls callback(data)
โ†’
You process the products

4. Callback hell

Callbacks work fine for simple tasks. But when you chain multiple async operations โ€” each depending on the previous one โ€” the nesting gets out of control. This is called the pyramid of doom.

๐Ÿ›’
UrbanCart Order Flow
The pyramid of doom

To complete an UrbanCart order, you need to: authenticate the user โ†’ fetch their cart โ†’ validate stock โ†’ process payment โ†’ send confirmation. Each step depends on the previous one.

callback-hell.js Nested callbacks โ€” the pyramid of doom
The fix: Promises flatten the pyramid. Instead of nesting callbacks inside callbacks, you chain .then() calls. Each step returns a Promise, keeping the code flat and readable.

5. Promises

A Promise is an object that represents the eventual result of an async operation. It can be in one of three states: pending (waiting), fulfilled (success), or rejected (error).

Promise states
Pending โณ
โ†’
Fulfilled โœ“
or
Pending โณ
โ†’
Rejected โœ—
promise.js Creating and consuming a Promise

Chaining Promises โ€” flattening the pyramid

The real power of Promises is chaining. Each .then() returns a new Promise, so you can chain them flat instead of nesting.

chain.js Promise chain โ€” flat, not nested

6. Promise.all

Sometimes you need to fetch multiple things at once โ€” products, user data, and reviews. They don't depend on each other, so why wait for one to finish before starting the next? Promise.all runs them in parallel.

promise-all.js Parallel fetching with Promise.all
Beware: If any Promise in Promise.all rejects, the entire thing rejects. Use Promise.allSettled if you want results from all โ€” even the ones that failed.

7. async/await

async/await is syntactic sugar over Promises. It makes async code look and read like synchronous code โ€” no .then() chains needed. This is the modern standard.

async-await.js Clean async code with async/await
๐Ÿ”—

.then() chains

fetchData().then(data => ...).then(result => ...)
Works, but gets long. Each step adds another .then().

โœจ

async/await

const data = await fetchData();
Reads like sync code. No nesting. Modern standard.

8. Error handling

With async/await, you handle errors using try/catch โ€” the same pattern JavaScript uses for synchronous errors. This keeps error handling clean and co-located with the code that might fail.

errors.js try/catch with async/await
Best practice: Always wrap await calls in try/catch. Without it, rejected Promises throw unhandled errors that crash your app silently. Show users a friendly message instead of a blank screen.

๐Ÿ› ๏ธ Try It Yourself #1

See the async progression in action. This editor simulates fetching UrbanCart products three ways: setTimeout with a callback, then a Promise, then async/await. Run it and watch the output appear after delays.

๐Ÿ› ๏ธ Try It โ€” Async Progression
Output

๐Ÿ› ๏ธ Try It Yourself #2

Use Promise.all to fetch product details, reviews, and shipping info in parallel. All three requests start at the same time โ€” the total wait is only as long as the slowest one.

๐Ÿ› ๏ธ Try It โ€” Promise.all in Parallel
Output

Test your knowledge

Question 1 of 5
Why is JavaScript called "single-threaded"?
Question 2 of 5
What is "callback hell"?
Question 3 of 5
What are the three possible states of a Promise?
Question 4 of 5
What happens if one Promise in Promise.all([p1, p2, p3]) rejects?
Question 5 of 5
What keyword must be placed before a function declaration to use await inside it?
0
/5
Great job!
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

You just mastered async JavaScript.
Now build a full-stack career.

Join the Best AI Programs โ€” three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses โ†’