Sub topic 8
Asynchronous I/O with Promises and async/await
This chapter assumes you can write functions and objects in JavaScript, that you have seen a promise before, and that you have read the previous chapter on the event loop. Here you will use that model for real input and output (I/O), such as reading files and making network requests.
Why I/O is asynchronous
Reading a file or fetching a URL takes milliseconds or longer, and during that time the CPU has nothing to do. Both runtimes hand the wait to the host. In the browser, the network stack does the waiting. In Node.js, the libuv library and the operating system do it. Your code gets a promise back immediately. When the data arrives, the runtime settles the promise, and your continuation runs as a microtask. The main thread stays free in the meantime.
Reading a file in Node.js
Node.js has callback, synchronous, and promise versions of its file APIs. For new code, use node:fs/promises.
// read.mjs (run with: node read.mjs, next to a data.txt file)
import { readFile } from 'node:fs/promises';
const text = await readFile(new URL('./data.txt', import.meta.url), 'utf8');
console.log(text.length);Top-level await like this works only in ES modules. In a CommonJS file, wrap the code in an async function.
Fetching data in the browser and Node.js
fetch is available globally in browsers and in Node.js 18 and later. Note that it involves two awaits: one for the response headers and one for the body.
// fetch-user.mjs
async function getUser(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}
try {
const user = await getUser(1);
console.log(user.name);
} catch (err) {
console.error('Request failed:', err.message);
}fetch rejects only on network failure. A 404 or 500 status still resolves, so you have to check response.ok yourself.
Sequential versus parallel
Each await pauses until its promise settles. If two operations do not depend on each other, start them both and then await them together.
// parallel.mjs
import { readFile } from 'node:fs/promises';
const files = ['a.txt', 'b.txt', 'c.txt'].map(
(name) => new URL(`./${name}`, import.meta.url)
);
// Parallel: all reads start immediately
const contents = await Promise.all(files.map((f) => readFile(f, 'utf8')));
console.log(contents.map((c) => c.length));
// Tolerant of failures: one missing file does not reject the whole batch
const results = await Promise.allSettled(files.map((f) => readFile(f, 'utf8')));
for (const r of results) {
console.log(r.status, r.status === 'fulfilled' ? r.value.length : r.reason.code);
}| Combinator | Resolves when | Rejects when |
|---|---|---|
| `Promise.all` | every promise fulfills | any promise rejects (fails fast) |
| `Promise.allSettled` | every promise settles | never |
| `Promise.race` | the first promise settles | the first settled promise rejected |
| `Promise.any` | the first promise fulfills | all promises reject |
Common errors
- Forgetting
await. The variable holds aPromiseobject instead of the data, and errors escape yourtry/catch. - Using
asynccallbacks withforEach.forEachignores the returned promises, so the code after the loop runs before the work finishes. Usefor...ofwithawaitfor sequential work, orPromise.allwithmapfor parallel work. - Unhandled rejections. In Node.js 15 and later, an unhandled rejection crashes the process by default. Browsers log it and fire an
unhandledrejectionevent. Always attach acatchor await the promise inside atryblock. - Awaiting in a loop by accident.
for (const f of files) await readFile(f)runs the reads one after another. That is correct when order matters and slow when it does not.
Exercise
This code prints "done" before any file is read. Why, and how do you fix it so all reads run in parallel and "done" prints last? files.forEach(async (f) => { await readFile(f, 'utf8'); }); console.log('done');
Show answer
forEach does not wait for the promises the async callback returns, so console.log runs right away. Replace the line with: await Promise.all(files.map((f) => readFile(f, 'utf8'))); and then call console.log('done').
Exercise
A fetch to a URL that returns HTTP 404 does not reach your catch block. Why not?
Show answer
fetch rejects only on network-level failures. An HTTP error status still resolves with a Response, so you have to check response.ok (or response.status) and throw the error yourself.