Sub topic 8
Asynchronous I/O with Promises and async/await
This chapter assumes you can write JavaScript functions, have seen a promise before, and know the event loop order from the previous chapter: synchronous code runs first, then microtasks, then tasks. The focus here is on doing real I/O: network requests in the browser, file reads in Node.js, and the patterns and mistakes that apply in both.
Where the I/O Actually Happens
The JavaScript engine has no network or disk access of its own. When you call fetch or readFile, the runtime starts the operation outside the engine. In the browser, the network stack does the work. In Node.js, the operating system or libuv's thread pool does it. The runtime immediately hands your code a promise, an object that stands for a result that does not exist yet. When the operation finishes, the runtime settles the promise, and any code waiting on it runs as a microtask.
That model is the same in both runtimes. Only the APIs that start the operations differ.
A promise that is fulfilled or rejected is called settled. Calling resolve or reject a second time does nothing, which is why a promise works well as a one-shot result.
From then-chains to async/await
The same request can be written with .then callbacks or with async/await. Both forms produce the same promises and the same microtasks.
// then-chain style
function getUserName(id) {
return fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then((user) => user.name);
}
// async/await style
async function getUserNameAsync(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const user = await response.json();
return user.name;
}
getUserNameAsync(1).then(console.log, console.error);These rules hold for any async function:
- It always returns a promise. A
return valuefulfills it, and athrowrejects it. awaitpauses only that function. The rest of the program, including the event loop, keeps running.- Code after an
awaitresumes in a microtask once the awaited promise settles.
Reading Files in Node.js
Node.js has three styles of file API: synchronous (readFileSync), callback (fs.readFile), and promise-based (node:fs/promises). The synchronous calls block the event loop until the disk responds. That is fine in a startup script and harmful inside a server handling many requests. In new code, use the promise API.
// config.mjs (run with: node config.mjs, next to a config.json file)
import { readFile, writeFile } from 'node:fs/promises';
const configUrl = new URL('./config.json', import.meta.url);
try {
const raw = await readFile(configUrl, 'utf8');
const config = JSON.parse(raw);
config.lastRun = new Date().toISOString();
await writeFile(configUrl, JSON.stringify(config, null, 2));
console.log('Updated config:', config);
} catch (err) {
if (err.code === 'ENOENT') {
console.error('config.json not found');
} else {
throw err;
}
}Node.js file errors carry a string code property such as ENOENT (file missing) or EACCES (permission denied). Check it instead of parsing the message text. The await at the top level works only because this is an ES module. In a CommonJS file you must wrap the code in an async function.
Older callback APIs can be converted with util.promisify, which works for any function whose last argument is a Node-style (err, result) callback:
// promisify.mjs
import { promisify } from 'node:util';
import { exec } from 'node:child_process';
const execAsync = promisify(exec);
const { stdout } = await execAsync('node --version');
console.log('Node version:', stdout.trim());For APIs that do not follow that convention, wrap them in new Promise yourself:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await sleep(500);
console.log('half a second later');Node.js also ships this helper as setTimeout from node:timers/promises.
Sequential versus Parallel
The most common performance mistake with await is accidental serialization. Each await in a loop waits for the previous operation to finish before starting the next one.
// parallel.mjs
import { readFile } from 'node:fs/promises';
const names = ['a.txt', 'b.txt', 'c.txt'];
const urlFor = (name) => new URL(`./${name}`, import.meta.url);
// Sequential: total time is roughly the sum of all reads
const sequential = [];
for (const name of names) {
sequential.push(await readFile(urlFor(name), 'utf8'));
}
// Parallel: all reads start at once; total time is roughly the slowest read
const parallel = await Promise.all(
names.map((name) => readFile(urlFor(name), 'utf8')),
);
console.log(sequential.length, parallel.length);The parallel version works because names.map calls readFile three times right away, and each call starts its I/O immediately. Promise.all only waits. It does not start anything. Use the sequential form only when each step depends on the previous result, or when you need to limit load on a server.
Choosing a Combinator
| Combinator | Fulfills when | Rejects when | Typical use |
|---|---|---|---|
| `Promise.all` | every input fulfills (results in input order) | the first input rejects | load everything a page needs |
| `Promise.allSettled` | every input settles | never | batch jobs where partial failure is fine |
| `Promise.race` | the first input settles, if it fulfilled | the first input settles, if it rejected | racing work against a timer |
| `Promise.any` | the first input fulfills | every input rejects (`AggregateError`) | trying mirror servers |
Note that Promise.all rejecting does not stop the other operations. They keep running, and their results are discarded.
const results = await Promise.allSettled([
fetch('https://example.com/'),
fetch('https://invalid.invalid/'),
]);
for (const r of results) {
if (r.status === 'fulfilled') console.log('ok', r.value.status);
else console.log('failed', r.reason.message);
}Cancellation and Timeouts
A promise cannot be cancelled once it exists, but the operation behind it often can. Both runtimes support AbortController and AbortSignal, which are web standards. fetch, Node's readFile, addEventListener, and many other APIs accept a signal option.
export async function getJsonWithTimeout(url, ms) {
try {
const response = await fetch(url, { signal: AbortSignal.timeout(ms) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (err) {
if (err.name === 'TimeoutError') {
throw new Error(`Request to ${url} took longer than ${ms} ms`);
}
throw err;
}
}AbortSignal.timeout produces a TimeoutError. A manual controller.abort() produces an AbortError. Checking err.name lets you tell a cancellation apart from a real failure. Unlike Promise.race with a timer, an abort signal actually stops the request and frees its resources.
Error Handling and Unhandled Rejections
Inside an async function, try/catch catches rejected awaits the same way it catches synchronous throws. The return await in the timeout example is deliberate. A bare return response.json() would return the promise before it settles, so a rejection from json() would skip the surrounding catch.
A rejected promise that nothing handles is an unhandled rejection. The two runtimes treat it differently:
| Runtime | Default behavior | Hook for logging |
|---|---|---|
| Browser | logs an error in the console; the page keeps running | `window.addEventListener('unhandledrejection', ...)` |
| Node.js 15+ | prints the error and exits with a non-zero code | `process.on('unhandledRejection', ...)` |
// Node.js
process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection:', reason);
process.exitCode = 1;
});
Promise.reject(new Error('nobody caught me'));Common Mistakes
- Forgetting
await.const data = readFile(path)gives you a promise, not the contents. The bug shows up later as[object Promise]or asundefinedproperties. awaitinsideforEach.forEachignores the promises its callback returns, so the code after the loop runs before any of the work finishes. Usefor...offor sequential work orPromise.allwithmapfor parallel work.- Fire-and-forget calls. Calling an
asyncfunction without awaiting it means its errors become unhandled rejections. - Mixing sync and async file APIs.
existsSyncfollowed byawait readFileis a race: the file can disappear between the two calls. CallreadFiledirectly and handleENOENT. - Assuming
awaitmakes code parallel.awaitmakes code wait. Only starting several operations before awaiting them makes them run concurrently.
Exercise
This Node.js code is meant to print the total length of three files, but it prints 0. Explain why and fix it. let total = 0; ['a.txt', 'b.txt', 'c.txt'].forEach(async (name) => { const text = await readFile(name, 'utf8'); total += text.length; }); console.log(total);
Show answer
forEach does not wait for the promises returned by its async callback, so console.log runs synchronously before any read completes, while total is still 0. Fix it with Promise.all: const texts = await Promise.all(['a.txt', 'b.txt', 'c.txt'].map((name) => readFile(name, 'utf8'))); const total = texts.reduce((sum, t) => sum + t.length, 0); console.log(total);
Exercise
You call Promise.all with three fetch calls. The second rejects after 100 ms, and the others finish after 2 seconds. When does Promise.all reject, and what happens to the other two requests?
Show answer
It rejects at about 100 ms with the second request's error. The other two requests keep running to completion and their results are discarded, because Promise.all does not cancel anything. To actually stop them, pass a shared AbortController's signal to every fetch and call abort() in the catch block.
Exercise
A function ends with return response.json(); inside a try block whose catch logs parse errors. Malformed JSON never reaches the catch. Why, and what one-word change fixes it?
Show answer
Returning the promise exits the try block before the promise settles, so its later rejection goes to the caller instead of the local catch. Change it to return await response.json(); so the rejection is thrown inside the try block.