Promises and async await
Local practice: Node.js 22.16.0 on Linux x64; proposed teaching baseline 26.13.1 remains untested. Copy only the listed files into a fresh disposable directory. No dependency installation or external services required. These are static Node.js examples, not verified ByteMind runner tasks.
Follow a chain and an await
async function total(quantity) { return quantity * 250; }const pending = total(3).then(cents => cents + 50);console.log('pending result');console.log(await pending);Run:
node main.mjsExpected stdout:
pending result800Exit status: 0. Expected stderr: empty.
How it works
Promises begin pending and settle once. then returns another promise and can transform a value; a thrown error rejects the next promise. await resumes with a value or throws the rejection. For independent operations, start both before awaiting Promise.all; it preserves input order in its result array. For dependent operations, await the first result before starting the second. Even an already fulfilled promise resumes an await asynchronously.
Combine independent lookups
async function lookup(name, count) { return { name, count }; }const books = lookup('books', 3);const pens = lookup('pens', 5);const results = await Promise.all([books, pens]);console.log(results.map(item => item.name + ':' + item.count).join(', '));Run:
node main.mjsExpected stdout:
books:3, pens:5Exit status: 0. Expected stderr: empty.
Common mistake
An async function does not move CPU work to another thread. Also, Array.forEach ignores returned promises: use a for...of loop with await for serial work or a bounded group of promises for independent work.
Practice
Add a third independent lookup and compare the result order with a serial loop. Explain why adding async to a synchronous calculation does not make it parallel.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Promises and async await — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What does an async function return?
Promise.all returns successful results in which order?
Which pattern waits for each item before starting the next?