Promise and Async Programs
Promise and Async Programs — purpose and prerequisites
Async programs coordinate work that completes later using Promises and await. Promise.all starts multiple operations and returns their results in input order when they all fulfill. Use explicit failure handling; an exception within an async function rejects its returned Promise.
What you’ll learn
- Explain the purpose of promise and async programs.
- Identify the typed contract, runtime responsibilities and common pitfalls.
- Run the example and extend its behavior with a practical exercise.
How the idea works
Each async call produces a Promise<number>. Promise.all yields number[] and preserves the original order, irrespective of individual timing.
Promise.all rejects when an input rejects; it does not automatically cancel other operations already in progress.
Visualize the flow
Run the checked TypeScript example
This source was compiled using TypeScript 5.8.3 with strict checking, then executed with Node.js 22.16.0. Its stdout below is the actual captured output. The core logic is runnable without a framework or a remote API; integration-specific examples appear in a separate lab when needed.
TypeScript source
async function doubleLater(n: number): Promise<number> { return n * 2; }
async function main(): Promise<void> {
const result = await Promise.all([doubleLater(2), doubleLater(5), doubleLater(7)]);
console.log(result.join(", "));
}
main().catch(console.error);Verified output
4, 10, 14Compile: npx tsc --strict --target es2022 --module commonjs promise-async-programs.ts; run: node promise-async-programs.js. For examples importing node: modules, install @types/node as a development dependency; for browser or React projects use the separate lab setup.
Trace the execution
Each async call produces a Promise<number>. Promise.all yields number[] and preserves the original order, irrespective of individual timing.
Before editing the code, predict what the output will be for one changed input. Run it and compare your prediction with the actual result.
Common mistake and correction
Promise.all rejects when an input rejects; it does not automatically cancel other operations already in progress.
Determine whether the issue belongs to the type system, a trust boundary, or actual runtime behavior before choosing a correction.
Your turn: extend the example
Add a function that sometimes rejects and compare Promise.all with Promise.allSettled.
Record expected success and failure outcomes, run the code, and compare the observed behavior. Keep the exercise compatible with strict type checking.
Check your understanding
Key idea to remember
Each async call produces a Promise<number>. Promise.all yields number[] and preserves the original order, irrespective of individual timing.
Apply the same reasoning to the practice task, then integrate it into a real app only when the runtime and dependency setup are ready.
Reaching the recap and completing the quizzes are separate milestones.