Async JavaScript in Node.jsLesson 2.3
async/await in Node.js: writing async code that looks synchronous
async functions, await keyword, try/catch with async, top-level await in ESM, sequential vs parallel await, error propagation
async/await Is Syntactic Sugar Over Promises
An async function always returns a Promise. Inside it, await pauses execution of that function (not the event loop) until the awaited Promise resolves. Other code continues running while it waits.
const fs = require('fs').promises;
async function mergeFiles() {
try {
const a = await fs.readFile('a.txt', 'utf8');
const b = await fs.readFile('b.txt', 'utf8');
await fs.writeFile('out.txt', a + b);
console.log('Done');
} catch (err) {
console.error('Failed:', err.message);
}
}
mergeFiles();Sequential vs Parallel
Awaiting inside a loop runs iterations sequentially. Use Promise.all to parallelize:
// Sequential (slow):
for (const file of files) {
await processFile(file);
}
// Parallel (fast):
await Promise.all(files.map(file => processFile(file)));Top-Level Await
In ESM files you can use await at the top level without an async wrapper:
// app.mjs
const data = await fs.readFile('config.json', 'utf8');
const config = JSON.parse(data);