Introduction to Asynchronous JavaScript
Introduction to Asynchronous JavaScript — the core idea
JavaScript can begin work now and continue after a later event without blocking the entire program. TypeScript annotates asynchronous values, but it does not replace the event loop or make operations parallel by default. Compare synchronous statements with promise callbacks.
What you’ll learn
- Explain introduction to asynchronous javascript with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: The first log runs synchronously. The resolved Promise schedules its then callback as a microtask; execution continues to print end first. After the current stack is empty, the callback prints data.
Keep the boundary clear: Do not assume a .then callback runs inline merely because a Promise is already fulfilled.
See the idea as a flow
Run the complete TypeScript example
Save the code as asynchronous-javascript.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
console.log("start");
Promise.resolve("data").then(value => console.log(value));
console.log("end");Verified output
start
end
dataBuild: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable asynchronous-javascript.ts; run: node asynchronous-javascript.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
The first log runs synchronously. The resolved Promise schedules its then callback as a microtask; execution continues to print end first. After the current stack is empty, the callback prints data.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
Do not assume a .then callback runs inline merely because a Promise is already fulfilled.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Add another synchronous log and predict where it appears relative to the Promise callback.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
JavaScript can begin work now and continue after a later event without blocking the entire program.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.