Courses / Node.js: From First Script to Production / Chapter 4
Module 3 · Asynchronous and event-driven code · Chapter 4 of 27
Asynchronous Programming: Callbacks, Promises and async/await
Builds on Getting Started: What Node.js Is and Running Your First Script and Globals and Modules: process, CommonJS and ES Modules. Next up: Event-Driven Programming with EventEmitter.
Part 1 · Blocking and non-blocking I/O
Two ways to wait for a file
A page that shows exam results must read from disk and from a database for every student who opens it. How the program waits for those reads decides whether one slow read holds up everyone else.
I/O (input and output) means any work that goes outside your program: reading a file, calling a database, sending a network request. The disk or the network is much slower than the processor, so most of the time in an I/O call is spent waiting.
Node offers two styles for most I/O. A blocking (synchronous) call, such as readFileSync, stops your code until the answer is ready. The next line runs only after the read has finished. A non-blocking (asynchronous) call, such as readFile, starts the work and returns at once. You give it a function to call when the work is done, and your code carries on in the meantime. That function is a callback.
The names tell you which is which. A function that ends in Sync blocks. Its twin without the suffix does not.
Blocking is not wrong. A command-line tool that reads one config file at start-up can use readFileSync and be simpler for it. The problem appears in a server, where one thread serves everyone. While that thread is blocked, nobody else is served.