async Functions
async Functions — the core idea
An async function always returns a Promise, including when its return statement contains an ordinary value. Await waits within that async function, not by stopping the whole JavaScript runtime.
What you’ll learn
- Explain async functions 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: double(6) produces a Promise that fulfills with 12. main awaits it, prints 12, and then finishes its own Promise<void>. The calculation itself is synchronous, but the return is promise-wrapped.
Keep the boundary clear: An async keyword does not make CPU-heavy loops non-blocking; expensive synchronous work still holds the event-loop thread.
See the idea as a flow
Run the complete TypeScript example
Save the code as async-functions.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
async function double(value: number): Promise<number> { return value * 2; }
async function main(): Promise<void> {
console.log(await double(6));
}
main().catch(console.error);Verified output
12Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable async-functions.ts; run: node async-functions.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
double(6) produces a Promise that fulfills with 12. main awaits it, prints 12, and then finishes its own Promise<void>. The calculation itself is synchronous, but the return is promise-wrapped.
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
An async keyword does not make CPU-heavy loops non-blocking; expensive synchronous work still holds the event-loop thread.
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
Write async function greet(name:string): Promise<string> and await its greeting.
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
An async function always returns a Promise, including when its return statement contains an ordinary value.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.