Node.js Promises & async/await
Most Node.js APIs are asynchronous: reading a file, querying a database or calling an API starts the work and returns immediately, and the result arrives later. Over the years Node has used three styles to deliver that later result. Modern code uses promises with async/await, but you will still meet the older styles in existing code and libraries.
From callbacks to promises
The original Node style is the error-first callback: the last argument is a function called with (err, result).
const fs = require('node:fs');
fs.writeFile('note.txt', 'callbacks!', (err) => {
if (err) return console.log('write failed', err.message);
fs.readFile('note.txt', 'utf8', (err, text) => {
if (err) return console.log('read failed', err.message);
console.log('read:', text);
fs.unlink('note.txt', (err) => {
if (err) return console.log('delete failed');
console.log('deleted');
});
});
});read: callbacks!
deleted
Each step nests one level deeper, and every level needs its own error check. With many steps this becomes the infamous callback pyramid. Promises flatten it.
A promise is an object representing a value that will exist in the future. It is pending at first, then becomes either fulfilled (with a value) or rejected (with an error). Node's promise-based APIs live in modules such as node:fs/promises, node:timers/promises, node:stream/promises and node:dns/promises.
import { writeFile, readFile, unlink } from 'node:fs/promises';
async function main() {
await writeFile('note.txt', 'promises!');
const text = await readFile('note.txt', 'utf8');
console.log('read:', text);
await unlink('note.txt');
console.log('deleted');
}
main().catch((err) => console.log('failed:', err.message));read: promises!
deleted
The same three steps, now reading top to bottom like synchronous code. await pauses only this async function — the event loop keeps serving other work in the meantime.
Tip: In ES modules (
.mjsor"type": "module") you can useawaitat the top level without wrapping code inasync function main().
Wrapping old callback APIs
util.promisify() turns any error-first-callback function into one that returns a promise. To create a promise from scratch, use new Promise((resolve, reject) => …):
const { promisify } = require('node:util');
function legacyDivide(a, b, callback) {
setTimeout(() => {
if (b === 0) callback(new Error('division by zero'));
else callback(null, a / b);
}, 10);
}
const divide = promisify(legacyDivide);
function delay(ms, value) {
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
(async () => {
console.log(await divide(10, 4));
console.log(await delay(20, 'waited 20 ms'));
try {
await divide(1, 0);
} catch (err) {
console.log('caught:', err.message);
}
})();2.5
waited 20 ms
caught: division by zero
Running tasks in parallel
await inside a loop runs tasks one after another. When tasks are independent, start them all and wait for them together — that's much faster.
| Combinator | Resolves when… | Rejects when… |
|---|---|---|
Promise.all(list) |
all fulfil (array of values, in input order) | any rejects |
Promise.allSettled(list) |
all have finished, either way | never |
Promise.race(list) |
the first one settles | the first one to settle rejects |
Promise.any(list) |
the first one fulfils | all reject (AggregateError) |
import { setTimeout as sleep } from 'node:timers/promises';
async function fetchUser(id, ms) {
await sleep(ms);
if (id === 0) throw new Error('user 0 does not exist');
return { id, name: `user${id}` };
}
const users = await Promise.all([fetchUser(1, 30), fetchUser(2, 10), fetchUser(3, 20)]);
console.log(users.map((u) => u.name));
const results = await Promise.allSettled([fetchUser(4, 10), fetchUser(0, 5)]);
for (const r of results) {
console.log(r.status, r.status === 'fulfilled' ? r.value.name : r.reason.message);
}
const fastest = await Promise.race([sleep(50, 'slow'), sleep(10, 'fast')]);
console.log('race winner:', fastest);
try {
await Promise.all([fetchUser(5, 10), fetchUser(0, 5)]);
} catch (err) {
console.log('all() failed:', err.message);
}[ 'user1', 'user2', 'user3' ]
fulfilled user4
rejected user 0 does not exist
race winner: fast
all() failed: user 0 does not exist
Promise.all keeps the input order even though user 2 finished first.
Timeouts and cancellation
Many Node APIs accept an AbortSignal. AbortSignal.timeout(ms) creates one that aborts automatically — an easy way to put a time limit on a slow operation. The rejection is an AbortError; its cause tells you why it was aborted:
import { setTimeout as sleep } from 'node:timers/promises';
try {
await sleep(1000, 'too late', { signal: AbortSignal.timeout(50) });
} catch (err) {
console.log(err.name, '-', err.cause.message);
}
const controller = new AbortController();
const job = sleep(1000, 'never', { signal: controller.signal });
controller.abort();
await job.catch((err) => console.log(err.name, '-', err.message));AbortError - The operation was aborted due to timeout
AbortError - The operation was aborted
Common mistakes
| Mistake | Fix |
|---|---|
forgetting await → you get a Promise { <pending> } |
await the call (or return the promise) |
await in a for loop for independent tasks |
Promise.all(items.map(fn)) |
array.forEach(async …) — forEach doesn't wait |
use for…of with await, or Promise.all |
no catch → unhandled rejection crashes Node |
try…catch around await, or .catch() |
| mixing callbacks and promises in one function | pick promises; wrap old APIs with promisify |
Test yourself
What is the first parameter of a Node-style callback?
- The result
- An error, or
nullon success - The options object
- The event name
Which combinator is best when you want every result, even if some tasks fail?
Promise.allPromise.racePromise.allSettledPromise.any
Why does items.forEach(async (x) => await save(x)) cause problems?
forEachcan't take arrow functionsforEachignores the returned promises, so nothing waits for the saves- It runs the saves twice
awaitis not allowed in arrow functions