Sub topic 3
Where Asynchronous Work Actually Happens: Host APIs
This chapter assumes you know JavaScript functions and callbacks, and that you have read the earlier chapters on single-threaded execution and the call stack. You should also be able to run snippets in a browser console or with Node.js.
The engine cannot wait
The JavaScript engine (V8, SpiderMonkey, JavaScriptCore) runs your code on one thread, using one call stack. The language itself has no built-in way to wait for a timer, read a file, or make a network request. If the engine had to do that waiting itself, the thread would sit idle and nothing else could run.
The engine runs inside a host environment. A host environment is the program that embeds the engine, such as a browser or Node.js. The host provides extra functions, called host APIs, and does the waiting on the engine's behalf.
| Host | Example APIs | Who does the work |
|---|---|---|
| Browser | `setTimeout`, `fetch`, DOM events, `XMLHttpRequest` | Browser timer, network, and input subsystems |
| Node.js | `setTimeout`, `fs.readFile`, `http`, `net` | libuv, the OS kernel, and a thread pool |
Look at what setTimeout actually is. It is not part of the ECMAScript language specification. The HTML standard defines it for browsers, and Node.js provides its own version.
The hand-off
Calling a host API is a synchronous function call. It registers your request and your callback with the host, then returns right away. The call stack moves on. The host does the waiting outside the JavaScript thread. When the result is ready, the host does not run your callback directly. It puts the callback in a queue, and the engine runs it later, once the stack is empty.
console.log('start');
setTimeout(() => {
console.log('timer callback');
}, 1000);
console.log('end');
// Output:
// start
// end
// (about one second later) timer callbackWhen setTimeout runs, the host starts a one-second timer and setTimeout returns. 'end' prints immediately. During that second the call stack is empty, so the thread is free for other work.
The same pattern applies to I/O in Node.js:
const fs = require('fs');
console.log('before read');
fs.readFile(__filename, 'utf8', (err, text) => {
if (err) throw err;
console.log('file length:', text.length);
});
console.log('after read');
// Output: before read, after read, file length: <number>The engine reads no bytes from disk. libuv hands the read to a worker thread, and the callback is queued after the read finishes.
Common misconceptions
- "The callback runs as soon as the work finishes." It does not. The callback waits in a queue until the call stack is empty. The next chapters cover this queue.
- "
setTimeoutis part of JavaScript." It belongs to the host. A bare engine shell such asd8may not provide it. - "Promises make code run on another thread." A promise only represents a result. The host does any real background work, and promise callbacks still run on the main thread.
Exercise
In a browser, a click handler calls fetch('/data').then(handle) and then runs a loop that takes 3 seconds. The server responds after 100 ms. When does handle run, and why?
Show answer
handle runs after the 3-second loop finishes. The browser's network layer receives the response at about 100 ms, outside the JavaScript thread, but the callback can only run once the call stack is empty, so it waits until the click handler returns.
Exercise
Why can setTimeout return before its delay has passed, even though JavaScript has only one thread?
Show answer
setTimeout only registers the timer and callback with the host and then returns. The host tracks the delay outside the JavaScript thread, so the engine never waits.