Sub topic 12
From Callbacks to Promises and async/await
This chapter assumes you already know the earlier material in this tutorial: error-first callbacks, the microtask queue, callback hell, and the reliability problems that come from handing your continuation to someone else's code. You should also have seen a Promise used with .then() at least once. All examples run in Node.js 18 or later.
Promises did not replace callbacks. A Promise is an object that holds callbacks and gives you rules about when they run. Once you see that, converting a callback API into a Promise API becomes a mechanical task, and the edge cases are easier to predict.
Promises Still Use Callbacks
A Promise is an object that represents a value that may not exist yet. It starts out pending. Later it becomes fulfilled with a value or rejected with a reason. When it leaves the pending state, we say it has settled.
You pass callbacks to a Promise in two places:
- The executor is the function you give to
new Promise(...). It runs synchronously, right away, and receivesresolveandreject. - The reactions are the functions you give to
.then(),.catch(), and.finally(). They run later, as microtasks.
The smallest example wraps setTimeout:
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
delay(500).then(() => console.log('half a second later'));Three callbacks appear here. setTimeout gets resolve as its callback. resolve is a callback that the Promise machinery created. The arrow function passed to .then() is a callback as well. What changed is who calls them and under what rules.
What Promises Fix
The previous chapter listed ways a callback can go wrong when you give it to code you don't control. A Promise enforces rules that guard against most of them.
| Problem with raw callbacks | What a Promise guarantees |
|---|---|
| Callback called twice | Settles once. Later `resolve` or `reject` calls do nothing |
| Called with both a result and an error | Ends in exactly one state: fulfilled or rejected |
| Sometimes sync, sometimes async | Reactions always run as microtasks, never synchronously |
| Never called | Not solved. A Promise can stay pending forever |
| Errors thrown in your handler get lost | A throw inside `.then()` rejects the next Promise in the chain |
The rule that a Promise settles only once is easy to show:
const p = new Promise((resolve, reject) => {
resolve(1);
resolve(2);
reject(new Error('ignored'));
});
p.then((v) => console.log('value', v));
console.log('sync code done');
// sync code done
// value 1The second resolve and the reject are ignored without any warning. The reaction also runs after the synchronous console.log, even though the Promise was already fulfilled when .then() was called. That is the consistent-async rule. You get it without writing queueMicrotask yourself.
Converting with util.promisify
Node's util.promisify takes a function that follows the error-first convention, with the callback as the last argument, and returns a version that returns a Promise.
const util = require('node:util');
const fs = require('node:fs');
const readFile = util.promisify(fs.readFile);
async function main() {
const text = await readFile('config.json', 'utf8');
console.log('Read', text.length, 'characters');
}
main().catch((err) => console.error(err.message));If config.json doesn't exist, the callback gets an ENOENT error. promisify turns that into a rejection, await throws it inside main, and the .catch() on main() handles it.
For Node core modules you rarely need promisify today. Most of them ship Promise versions, such as require('node:fs/promises'), require('node:timers/promises'), and require('node:dns/promises'). Use those first. Keep promisify for third-party or legacy callback APIs.
Writing the Wrapper by Hand
To understand promisify and its limits, write one yourself. First, a wrapper for one function:
const fs = require('node:fs');
function readFileAsync(path, encoding) {
return new Promise((resolve, reject) => {
fs.readFile(path, encoding, (err, data) => {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
}
readFileAsync('config.json', 'utf8')
.then((text) => console.log('Read', text.length, 'characters'))
.catch((err) => console.error('Failed:', err.message));Now make it general:
function promisify(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
fn.call(this, ...args, (err, value) => {
if (err) return reject(err);
resolve(value);
});
});
};
}
// Try it with a callback API
function addLater(a, b, callback) {
setTimeout(() => callback(null, a + b), 10);
}
const addAsync = promisify(addLater);
addAsync(2, 3).then((sum) => console.log('sum', sum)); // sum 5Note the regular function used for the returned wrapper and the fn.call(this, ...). They pass along whatever this the wrapper was called with. An arrow function would capture the this of the place where promisify ran, which is the wrong one.
Edge Cases When Promisifying
Lost this
promisify preserves this only when the wrapper is called as a method. If you pull a method off an object, you get the bug from the this chapter again:
const util = require('node:util');
const db = {
prefix: 'row-',
find(id, callback) {
setTimeout(() => callback(null, this.prefix + id), 0);
},
};
const findBroken = util.promisify(db.find);
findBroken(1).catch((err) => console.error('broken:', err.message));
// broken: Cannot read properties of undefined (reading 'prefix')
const find = util.promisify(db.find).bind(db);
find(1).then((row) => console.log(row)); // row-1The broken call fails because this is undefined inside find. Object literal methods are not in strict mode by default, but promisify calls the original with the wrapper's this, and a bare function call in a CommonJS module gives undefined there. Bind the promisified function, or promisify db.find.bind(db). Either way works.
Callbacks with more than one result
A Promise fulfills with one value. Some legacy APIs call back with (err, a, b). A generic promisify keeps only a. Library authors can fix this by attaching a custom implementation under util.promisify.custom, which util.promisify uses when it is present:
const util = require('node:util');
function measure(n, callback) {
setTimeout(() => callback(null, n, n * n), 0);
}
measure[util.promisify.custom] = (n) =>
new Promise((resolve, reject) => {
measure(n, (err, value, square) => {
if (err) return reject(err);
resolve({ value, square });
});
});
const measureAsync = util.promisify(measure);
measureAsync(4).then((r) => console.log(r)); // { value: 4, square: 16 }Node's own dns.lookup and setTimeout use this hook, so promisifying them gives a sensible result.
APIs that do not follow the convention
promisify assumes the callback is the last argument and that its first parameter is the error. Some APIs break both rules. setTimeout puts the callback first. Browser-style APIs often take separate success and failure callbacks. Wrap those by hand and map each callback to resolve or reject:
function legacyFetch(url, onSuccess, onFailure) {
setTimeout(() => {
if (url.startsWith('https://')) onSuccess({ url, status: 200 });
else onFailure(new Error('Only HTTPS is allowed'));
}, 0);
}
function fetchAsync(url) {
return new Promise((resolve, reject) => {
legacyFetch(url, resolve, reject);
});
}
fetchAsync('http://example.com').catch((err) => console.error(err.message));
// Only HTTPS is allowedThrows inside the wrapped callback
The Promise constructor turns a synchronous throw in the executor into a rejection. It cannot catch a throw that happens later, inside an asynchronous callback:
const p = new Promise((resolve, reject) => {
setTimeout(() => {
try {
resolve(JSON.parse('{bad json'));
} catch (err) {
reject(err);
}
}, 0);
});
p.catch((err) => console.error('caught:', err.name)); // caught: SyntaxErrorWithout the try/catch, the SyntaxError would escape as an uncaught exception and crash the Node process, and p would stay pending forever. When you do work inside the inner callback, guard it, or call resolve with the raw data and do the parsing in a .then() where throws are caught for you.
Flattening Callback Hell with async/await
async/await is syntax built on Promises. An async function always returns a Promise. await pauses the function until a Promise settles, then resumes it as a microtask. Here is the readConfig example from the callback-hell chapter, extended to read a second file named in the first:
const fs = require('node:fs/promises');
async function loadSettings(path) {
const config = JSON.parse(await fs.readFile(path, 'utf8'));
const overrides = JSON.parse(await fs.readFile(config.overridesPath, 'utf8'));
return { ...config, ...overrides };
}
loadSettings('config.json')
.then((settings) => console.log('Loaded keys:', Object.keys(settings)))
.catch((err) => console.error('Could not load settings:', err.message));One catch handles read errors and JSON.parse errors from both steps. There is no if (err) return callback(err) on each level, and the code reads top to bottom.
Sequential versus parallel
Each await waits before the next line starts. That is correct when step two depends on step one. When the steps are independent, start them all and then await them together:
const fs = require('node:fs/promises');
async function readAll(paths) {
const texts = await Promise.all(paths.map((p) => fs.readFile(p, 'utf8')));
return texts.map((t) => t.length);
}
readAll(['a.txt', 'b.txt'])
.then((lengths) => console.log(lengths))
.catch((err) => console.error(err.message));Promise.all rejects as soon as any one input rejects. Use Promise.allSettled when you want every result, successes and failures together.
Events and Promises
Event listeners can fire many times, and a Promise settles once, so the two don't map directly. For a one-time event, events.once returns a Promise that fulfills with an array of the event's arguments:
const { EventEmitter, once } = require('node:events');
const emitter = new EventEmitter();
async function waitForReady() {
const [port] = await once(emitter, 'ready');
console.log('ready on port', port);
}
waitForReady();
setTimeout(() => emitter.emit('ready', 8080), 10);
// ready on port 8080If the emitter emits 'error' first, the Promise rejects. For streams of repeated events, events.on returns an async iterator that you consume with for await...of.
Going the Other Way: util.callbackify
Sometimes you have an async function and have to pass it to an API that expects an error-first callback. util.callbackify does that conversion:
const util = require('node:util');
async function getUser(id) {
if (id < 0) throw new Error('Invalid id');
return { id, name: 'Ada' };
}
const getUserCb = util.callbackify(getUser);
getUserCb(1, (err, user) => {
if (err) return console.error(err.message);
console.log(user.name); // Ada
});Common Mistakes
- Forgetting
returnorawait. Code likeasync function f() { fs.readFile(p); }starts the read and drops the Promise. Errors become unhandled rejections, and the caller doesn't wait. - Wrapping something that already returns a Promise.
new Promise((res) => res(fetch(url)))works, but it is noise. Returnfetch(url)directly. - Unhandled rejections. Since Node 15, an unhandled rejection crashes the process by default. Every Promise chain needs a
.catch(), or atry/catcharound itsawait. - Mixing styles in one API. A function that both takes a callback and returns a Promise invites double handling. Choose one style per function.
Exercise
You run const stat = util.promisify(fs.stat); await stat('missing.txt'); inside an async function with no try/catch, and you call that function as check(); with nothing after it. What happens, and how do you fix it?
Show answer
fs.stat calls back with an ENOENT error, so the promisified call rejects and the await throws inside check. Because check() is called without .catch() or await, its returned Promise rejection is unhandled, and Node 15+ terminates the process. Fix it by wrapping the await in try/catch inside check, or by calling check().catch(handleError).
Exercise
Write a function timeout(promise, ms) that rejects with an Error('Timed out') if promise does not settle within ms milliseconds, and explain which callback problem this solves.
Show answer
function timeout(promise, ms) { let id; const timer = new Promise((_, reject) => { id = setTimeout(() => reject(new Error('Timed out')), ms); }); return Promise.race([promise, timer]).finally(() => clearTimeout(id)); } It handles the "callback never called" case, which Promises alone cannot detect: a wrapped API that never calls back leaves its Promise pending, and the race ensures the caller still gets a result. clearTimeout in finally stops the timer from keeping the process alive.
Exercise
A library exposes client.query(sql, callback) where the method reads this.connection. Your code const q = util.promisify(client.query); await q('SELECT 1'); throws "Cannot read properties of undefined". Why, and what are two fixes?
Show answer
util.promisify calls the original function with the this value of the promisified wrapper. Calling q as a bare function gives undefined for this, so this.connection fails. Fix it with util.promisify(client.query).bind(client), or util.promisify(client.query.bind(client)).