Sub topic 3
async/await: Promises with Synchronous-Looking Code
This chapter assumes you already know how to chain promises with then and catch and how errors move through a chain.
async/await
An async function always returns a promise. Inside it, await pauses the function until a promise settles. If the promise fulfills, await gives you its value. If it rejects, await throws the error, so you handle it with try/catch.
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
async function sequential() {
const a = await delay(100, 'a');
const b = await delay(100, 'b');
return [a, b]; // about 200 ms total
}
async function parallel() {
const [a, b] = await Promise.all([delay(100, 'a'), delay(100, 'b')]);
return [a, b]; // about 100 ms total
}
async function main() {
try {
console.log(await sequential());
console.log(await parallel());
} catch (err) {
console.error(err);
}
}
main();When Callbacks Run: The Microtask Queue
Promise callbacks run as microtasks. Microtasks run after the current synchronous code finishes and before timer callbacks.
console.log('1');
setTimeout(() => console.log('4'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('2');
// Output: 1, 2, 3, 4Turning Callback APIs into Promise APIs
You can wrap an error-first callback in new Promise yourself, or use Node's util.promisify to do the same thing.
const fs = require('node:fs');
const { promisify } = require('node:util');
function readFileManual(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => (err ? reject(err) : resolve(data)));
});
}
const readFileP = promisify(fs.readFile);
readFileManual(__filename).then((t) => console.log(t.length));
readFileP(__filename, 'utf8').then((t) => console.log(t.length));Unhandled Rejections
A rejection that has no handler attached is reported as unhandled. In recent Node.js versions, an unhandled rejection crashes the process by default. You can register a global handler as a safety net, but it does not replace a local catch.
process.on('unhandledRejection', (reason) => {
console.error('Unhandled:', reason);
});
Promise.reject(new Error('forgotten'));In browsers, listen for the unhandledrejection event on window.
Thenables
A thenable is any object that has a then method. Promise.resolve, await and returning a value from then all adopt a thenable's eventual result.
const thenable = { then(resolve) { resolve(42); } };
Promise.resolve(thenable).then((v) => console.log(v)); // 42Common Mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Not returning the promise inside `then` | The next step runs early and receives `undefined` | Use `return` or a concise arrow body |
| Writing `await` on independent tasks one after another | The tasks run in sequence, which is slower | Start them all, then `await Promise.all` |
| Leaving off the final `catch` | The rejection goes unhandled | End every chain with `catch` or wrap it in `try/catch` |
| Using `forEach` with an async callback | Nothing waits for the callbacks | Use `for...of` or `Promise.all(arr.map(...))` |
Exercise
What does this log, and in what order? setTimeout(() => console.log('t'), 0); (async () => { console.log('a'); await null; console.log('b'); })(); console.log('c');
Show answer
a, c, b, t. The async function runs synchronously until the first await, so 'a' logs first. Then 'c' logs. 'b' runs as a microtask, and the timer callback 't' runs last.
Exercise
Two independent fetches each take 300 ms. Why do const x = await f1(); const y = await f2(); take about 600 ms, and how do you bring that down to about 300 ms?
Show answer
Each await waits for its fetch to finish before the next one starts. Start both first and await them together: const [x, y] = await Promise.all([f1(), f2()]);