Part III. Time7 min · en inglés

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.

Gratis, solo falta un paso

El resto del libro es gratis

Deja tu correo y te mando un enlace para confirmarlo. Después del clic, todos los capítulos se abren aquí, en este dispositivo, durante un año. Cuando salga un libro nuevo, escribiré a esa dirección; responde “basta” a cualquier correo y no vuelvo a escribir.

¿Tienes cuenta INITE? Entra y el libro se abre sin correo.

No se cobra nada por el libro. Si quieres apoyarlo, puedes donar desde cualquier capítulo.

Cómo se guarda la dirección