JS Asynchronous Programming
Control Flow is the order in which statements are executed in a program.
By default, JavaScript runs code from top to bottom and left to right.
Asynchronous programming changes when some code runs.
How JavaScript Runs Code
JavaScript executes code one line at a time.
Each line must finish before the next line runs.
Example:
console.log("A");
console.log("B");
console.log("C");
The output is always A, B, C.
This is called synchronous code.
The Problem With Blocking Code
Some tasks take time.
Examples include network requests, timers, and user input.
If JavaScript waited for these tasks, the page would freeze.
A frozen page is a broken page.
Why JavaScript Uses Async
JavaScript uses asynchronous code to stay responsive.
Long tasks are started and finished later.
The rest of the program continues running.
Example:
console.log("Start");
setTimeout(function() {
console.log("Later");
}, 1000);
console.log("End");
Note
Understanding async is about understanding time.
The output is Start, End, Later.
Async code does not block execution.
What Asynchronous Means
Asynchronous code runs after the current code finishes.
It does not run immediately.
JavaScript registers the task and moves on.
- Timers run later.
- Events run when triggered.
- Network requests run when data arrives.
A Simple Timeline
Think of async code as a to-do list.
JavaScript finishes what it is doing first.
When the task is ready, JavaScript comes back to it.
Async does not mean parallel.
It means deferred.
Common Beginner Confusion
Beginners expect async results immediately.
Example mistake:
let result;
setTimeout(function() {
result = 5;
}, 1000);
console.log(result);
The value is undefined.
The async code has not finished yet.
The Async Building Blocks
JavaScript handles async using a few core tools.
- Callbacks
- Promises
asyncandawait
Each tool exists to solve problems from the previous one.
What You Will Learn Next
This tutorial builds async step by step.
- Why callbacks were created.
- How promises represent future values.
- Why
asyncandawaitare preferred. - How to debug async code.
You do not need to memorize anything yet.
You need to understand the flow.
Next: JavaScript Callbacks
The first async solution in JavaScript was callbacks.
The next page explains what they are and why they caused problems.