Sub topic 3
Where Asynchronous Work Actually Happens: Host APIs
This chapter assumes you can write functions and callbacks, use basic Promises, and run scripts in a browser console or with Node.js. The previous chapters set up two ideas. JavaScript runs one piece of code at a time, and the call stack tracks which function is running now. That leaves an open question. If only one thing runs at a time, who waits for the timer, downloads the file, or listens for the click?
The answer is the host: the environment that embeds the JavaScript engine.
The Engine and the Host Are Different Things
A JavaScript engine is the program that parses and executes JavaScript. Examples are V8 (Chrome, Node.js, Deno), SpiderMonkey (Firefox), and JavaScriptCore (Safari). The engine implements the ECMAScript specification: syntax, objects, functions, closures, Promises, and the call stack.
The ECMAScript specification does not define setTimeout, fetch, addEventListener, or fs.readFile. Those come from the host:
- In a browser, the host APIs are the Web APIs, defined by the HTML, DOM, and Fetch standards.
- In Node.js, the host APIs are Node's modules (
fs,net,http,crypto, timers), mostly built on a C library called libuv.
When your code calls setTimeout, the engine does not wait for anything. It calls into host code, which records the request and returns right away. The waiting happens in the host, outside your JavaScript thread.
The Lifecycle of a Host API Call
Every callback-based host API follows the same steps:
- Hand-off. Your code calls the API with some arguments and a callback. The host records the request.
- Immediate return. The API returns at once, often with a handle such as a timer ID. Your synchronous code keeps running.
- Background work. The host does the slow part on its own machinery: OS timers, network sockets, disk I/O, or helper threads.
- Completion. When the work finishes, the host does not interrupt your running code. It puts the callback in a queue.
- Execution. Later, when the call stack is empty, the event loop takes the callback from the queue and runs it on the main thread.
Steps 4 and 5 are the subject of the next two chapters. For now the key point is that host work can happen in parallel with your JavaScript, but your callbacks never run in parallel with it.
Seeing the Hand-off in Action
This script works in a browser console or in Node.js. It starts two 100 ms timers and checks how long the whole thing takes.
const start = Date.now();
const elapsed = () => Date.now() - start;
const id1 = setTimeout(() => console.log('first timer at', elapsed(), 'ms'), 100);
const id2 = setTimeout(() => console.log('second timer at', elapsed(), 'ms'), 100);
console.log('both timers registered at', elapsed(), 'ms');
console.log('setTimeout returned', typeof id1, typeof id2);
// Typical output:
// both timers registered at 0 ms
// setTimeout returned number number (browser; Node.js prints object object)
// first timer at 101 ms
// second timer at 101 msBoth timers fire around 100 ms, not 200 ms. The host waited for both at the same time while the JavaScript thread did other work. The return value is a number in browsers and a Timeout object in Node.js. In both cases it is a handle to work that lives in the host.
What Hosts Provide, and Where the Work Runs
| API | Host | Where the background work happens | How the result comes back |
|---|---|---|---|
| `setTimeout`, `setInterval` | Browser, Node.js | Host timer system | Callback queued as a task |
| `fetch` | Browser, Node.js 18+ | Browser network process; libuv sockets in Node | Promise resolved by the host |
| `addEventListener('click', ...)` | Browser | Browser input handling | Callback queued as a task per event |
| `fs.readFile` | Node.js | libuv thread pool | Callback queued when the read completes |
| `net` / `http` sockets | Node.js | OS async I/O (epoll, kqueue, IOCP) | Callback or event emitted on the main thread |
| `crypto.pbkdf2`, `zlib` (async) | Node.js | libuv thread pool | Callback queued on completion |
Node.js handles different kinds of work in different ways. Network I/O uses the operating system's non-blocking facilities, so one thread can watch thousands of sockets. File system calls and some CPU-heavy built-ins (crypto, zlib, DNS lookups through dns.lookup) have no portable non-blocking OS interface, so libuv runs them on a small pool of worker threads. That pool has 4 threads by default.
The Thread Pool Has Limits
This Node.js script makes the thread pool visible. Each pbkdf2 call is deliberately slow.
// Save as pool.js and run: node pool.js
const crypto = require('crypto');
const start = Date.now();
for (let i = 1; i <= 5; i++) {
crypto.pbkdf2('secret', 'salt', 200000, 64, 'sha512', () => {
console.log(`hash ${i} done at ${Date.now() - start} ms`);
});
}
console.log('all 5 requests handed to libuv');On a machine with at least four cores you will usually see "all 5 requests handed to libuv" first. Hashes 1 to 4 then finish at about the same time, and hash 5 finishes roughly twice as late. Only four threads exist, so the fifth job waits for a free one. Run UV_THREADPOOL_SIZE=5 node pool.js on a machine with five or more cores and all five finish together. Exact timings depend on your CPU.
Common Misconceptions
"Asynchronous means my JavaScript runs in parallel"
The host's work can run in parallel. Your callbacks cannot. Every callback runs on the single main thread, one at a time, each to completion. Two fetch responses that arrive at the same moment still have their handlers run one after the other.
"The callback runs the moment the work finishes"
The host only queues the callback. If the call stack is busy with a long loop, the callback waits. This is why a timer's delay is a minimum, a point covered in detail in a later chapter.
"Wrapping code in a callback or Promise makes it non-blocking"
Only work that is actually handed to the host runs off the main thread. Your own CPU-bound code always runs on the main thread, wherever you put it:
function slowSum(n) {
let total = 0;
for (let i = 0; i < n; i++) total += i;
return total;
}
// Still blocks the main thread. The Promise adds no background thread.
new Promise((resolve) => resolve(slowSum(1e9))).then((sum) => {
console.log('sum', sum);
});
console.log('this line waits until slowSum finishes');The Promise executor runs synchronously, so slowSum blocks before the final console.log. The same applies to synchronous host variants such as fs.readFileSync or crypto.pbkdf2Sync. They do their work on the main thread and block it until done.
"Every function that takes a callback is asynchronous"
Array.prototype.map, forEach, and sort take callbacks but call them synchronously, before they return. A callback is asynchronous only when a host API (or a Promise) arranges for it to run later.
Why This Design Works
Handing slow work to the host keeps the main thread free for short pieces of JavaScript. A web server can have many requests waiting on the database at once, and each one costs only a small record in the host. A page can download images while it responds to scrolling. The trade-off is that your code must be written as callbacks or awaited Promises, and anything slow you do on the main thread still freezes everything else.
Exercise
In a browser, you call setTimeout(cb, 50) and then immediately run a synchronous loop that takes 300 ms. Who tracks the 50 ms, and when does cb run relative to the loop?
Show answer
The browser's timer system, outside the JavaScript thread, tracks the 50 ms. After 50 ms the host queues cb, but it cannot run until the loop finishes and the call stack is empty, so cb runs after about 300 ms.
Exercise
A Node.js script starts 8 fs.readFile calls on large files and, at the same time, 100 outgoing HTTP requests. Which of these use the libuv thread pool, and how many file reads can be in progress at once with default settings?
Show answer
The fs.readFile calls use the thread pool. The HTTP sockets use the operating system's non-blocking network I/O, though DNS resolution through dns.lookup also uses the pool. With the default pool size of 4, at most four file system operations run at once, and the rest wait for a free thread.
Exercise
Is Promise.resolve(42).then(console.log) an example of a host API doing background work? Explain.
Show answer
No. Promises are defined by ECMAScript and implemented by the engine. No host work is involved, so the engine schedules the then callback itself. Only APIs such as timers, fetch, DOM events, and Node's I/O modules hand work to the host.