Part III. Time7 min

10

Continuations

I learned to program on Meteor and for quite a long time had no idea that asynchrony in JavaScript could be difficult at all. Code on the server looked the way code looks in a textbook: read from the database, compute, write back, line by line, top to bottom. Why it worked that way I will explain in the next chapter. I learned about the difficulties when I stepped outside Meteor and saw how the very same code is written in plain Node. Before async/await arrived, the community called such code callback hell, and the name was deserved.

To understand where that hell came from, you need one concept from programming language theory. A continuation is everything the program will do after the current line. When an ordinary synchronous program says const user = db.find(id) followed by ten more lines, those ten lines are the continuation. The programmer does not need to store it; the call stack does that for free: while db.find runs, somewhere in memory there is a note saying where to return and with which variables to continue.

Node cancelled this free service. If a database read cannot be waited for, because there is only one thread and it has no right to wait, then the read function must return control immediately and deliver the result later. But then what should happen to those ten lines? Node’s answer was blunt: wrap them in a function and hand it to the read function, which will call it when the data arrives. The programmer started packing up the rest of the program and passing it from hand to hand. In theory this is called continuation-passing style, and before Node it was mostly compilers that wrote this way, transforming programs into this form automatically. In Node, people wrote this way.

Free, one step away

The rest of the book is free

Leave your email and I will send a link to confirm it. Once you click it, every chapter opens here, on this device, for a year. When a new book comes out I will write to this address; reply “stop” to any email and I will not write again.

Have an INITE account? Sign in and the book opens without an email.

I do not charge for the book. If you would like to support it, you can donate from any chapter.

How your email is stored