Sub topic 4
Asynchronous Callbacks: setTimeout and I/O
This chapter assumes you can write and call functions that accept callbacks, and that you know how synchronous callbacks such as map and forEach behave. You should also be able to run a script with Node.js, because the I/O examples use Node's fs module.
Synchronous vs. Asynchronous Invocation
A synchronous callback runs before the function that received it returns. forEach calls your callback once per element, and only after the last call does forEach return.
An asynchronous callback runs later. The function you pass it to stores the callback, starts some work, and returns right away. Your code keeps running. When the work finishes, or a timer expires, the runtime calls your callback.
The difference matters because it decides the order your code executes in. With a synchronous callback, the code after the call can rely on the callback having already run. With an asynchronous callback, it cannot.
Timers: setTimeout
setTimeout(callback, delay) asks the runtime to call callback after at least delay milliseconds. It returns immediately.
console.log('A');
setTimeout(() => console.log('C'), 0);
console.log('B');
// Output: A, B, CThe delay is 0, but C still prints last. A zero delay does not mean "now." It means "as soon as possible after the current synchronous code finishes." The callback waits in a queue until the call stack is empty. The next chapter explains how that queue works.
The delay is a minimum, not a guarantee. If synchronous code keeps the thread busy, the timer callback waits:
const start = Date.now();
setTimeout(() => {
console.log('Fired after', Date.now() - start, 'ms');
}, 100);
// Block the thread for about 500 ms
while (Date.now() - start < 500) {}
// Fired after ~500 msI/O Callbacks
Reading files, making network requests, and querying databases all take time. If JavaScript waited for each of these operations synchronously, the whole program would freeze. Node.js instead hands the operation to the system and calls your callback once the result is ready.
const fs = require('node:fs');
console.log('Before read');
fs.readFile(__filename, 'utf8', (err, data) => {
if (err) {
console.error('Read failed:', err.message);
return;
}
console.log('Read', data.length, 'characters');
});
console.log('After read');
// Before read
// After read
// Read ... charactersThe script reads its own file, so it runs as shown. After read prints before the file contents arrive, even though the read was started first. The err parameter follows a Node.js convention that a later chapter covers in detail.
Common Mistakes
Returning a value from an async callback
A return inside the callback goes back to whoever called the callback, which is the runtime. Your function never receives that value.
const fs = require('node:fs');
function getLength(path) {
fs.readFile(path, 'utf8', (err, data) => {
return data.length; // goes nowhere useful
});
}
console.log(getLength(__filename)); // undefinedThe fix is to accept a callback of your own and pass the result to it:
const fs = require('node:fs');
function getLength(path, callback) {
fs.readFile(path, 'utf8', (err, data) => {
if (err) return callback(err);
callback(null, data.length);
});
}
getLength(__filename, (err, length) => {
if (err) return console.error(err.message);
console.log('Length:', length);
});Once a value arrives asynchronously, every function that needs it must also deliver its result asynchronously.
Using a variable before the callback sets it
let result;
setTimeout(() => { result = 42; }, 0);
console.log(result); // undefinedAny code that depends on result has to run inside the callback, or in something the callback calls.
Throwing inside an async callback
A try/catch placed around setTimeout or fs.readFile cannot catch errors thrown inside the callback. By the time the callback runs, the try block has already exited. Handle errors inside the callback itself.
Summary
| Aspect | Synchronous callback | Asynchronous callback |
|---|---|---|
| When it runs | Before the outer function returns | After current synchronous code finishes |
| Examples | `map`, `filter`, `forEach` | `setTimeout`, `fs.readFile`, network requests |
| Can return a result to caller | Yes, through the outer function | No, it must pass the result to another callback |
| Caught by surrounding `try/catch` | Yes | No |
Exercise
Predict the output of this script and explain the order. console.log('1'); setTimeout(() => console.log('2'), 10); setTimeout(() => console.log('3'), 0); console.log('4');
Show answer
The output is 1, 4, 3, 2. The two console.log calls outside the timers run synchronously first, so 1 and 4 print. The timer callbacks run only after the synchronous code finishes. The 0 ms timer expires before the 10 ms timer, so 3 prints before 2.
Exercise
A colleague writes function loadName() { let name; setTimeout(() => { name = 'Ada'; }, 0); return name; } and finds that loadName() returns undefined. Rewrite it so the caller can get the name.
Show answer
Accept a callback and call it with the value once it is set: function loadName(callback) { setTimeout(() => callback('Ada'), 0); } and then call loadName((name) => console.log(name)). The original returns before the timer callback runs, so name is still undefined at the return.