Callback Functions 2
A function that does slow work, such as reading a file or waiting on a server, cannot return its result straight away. Before promises, the usual answer was to accept callbacks and call one of them when the work finished. This page builds such functions, using setTimeout() to stand in for the slow work. Callback Functions covers the basics.
Separate success and failure callbacks
Section titled “Separate success and failure callbacks”One style takes two callbacks, and calls the first with the result or the second with an error:
const users = { 7: { name: 'Priya', plan: 'family' } };
function findUser(id, onFound, onMissing) { setTimeout(() => { const user = users[id]; if (user) { onFound(user); } else { onMissing(new Error(`No user with id ${id}`)); } }, 20);}
const showUser = (user) => console.log(`${user.name} is on the ${user.plan} plan`);const showError = (err) => console.log(err.message);
findUser(7, showUser, showError);findUser(9, showUser, showError);This prints:
Priya is on the family planNo user with id 9findUser() returns undefined at once, and the answer arrives later through a callback. Browser APIs such as navigator.geolocation.getCurrentPosition() use this style.
Error-first callbacks
Section titled “Error-first callbacks”Node’s older APIs, such as fs.readFile(), use a single callback instead. Its first parameter is an error, or null when nothing went wrong, and the result comes after it:
const stock = { apples: 12, pears: 0 };
function checkStock(item, callback) { setTimeout(() => { if (!(item in stock)) { callback(new Error(`Unknown item: ${item}`)); return; } callback(null, stock[item]); }, 20);}
checkStock('apples', (err, count) => { if (err) { console.log(err.message); return; } console.log(`apples in stock: ${count}`);});
checkStock('plums', (err, count) => { if (err) { console.log(err.message); return; } console.log(`plums in stock: ${count}`);});This prints:
apples in stock: 12Unknown item: plumsPutting the error first means that the caller cannot forget it is there, and the return after the error is reported stops checkStock() from going on to call the callback a second time.
Errors must travel through the callback
Section titled “Errors must travel through the callback”A try...catch around a call to checkStock() cannot catch an error thrown inside the timer, because the try block has finished by the time the timer fires. That is why both styles hand the error to a callback as a value rather than throwing it. An uncaught throw inside the timer would end a Node program, and in a browser it would be logged to the console with nothing able to handle it.
From callbacks to promises
Section titled “From callbacks to promises”Callbacks become hard to follow when one step depends on the one before, because each step nests inside the last. Promises and async/await replace this, and a callback function can be wrapped in a promise once and then used with await:
function checkStockAsync(item) { return new Promise((resolve, reject) => { checkStock(item, (err, count) => (err ? reject(err) : resolve(count))); });}
(async () => { try { console.log(await checkStockAsync('apples')); console.log(await checkStockAsync('pears')); console.log(await checkStockAsync('plums')); } catch (err) { console.log(err.message); }})();This prints:
120Unknown item: plumsNode’s util.promisify() does the same wrapping for any error-first function. Async Await covers the promise side.
Steve Griffith covers this topic in his video What are Callback Functions and How Do They Work?.