JavaScript: From Closures to Autonomous Systems

Capítulo 12. Time as Part of the Program

Part III. Time7 min · en inglés

12

Time as Part of the Program

By 2017 asynchronous JavaScript code could once again be read top to bottom. But async/await answered only the question of how to write waiting without a staircase. Three more questions remained, and all of them are about time: how to stop work that is no longer needed, how long work that was started and forgotten lives, and what happens to waiting functions if the process suddenly dies. While a program is short and lives in one process, these questions need not be asked. On a server that runs for months and serves thousands of requests at once, there is no way around them.


Let us start with cancellation. A promise in JavaScript cannot be cancelled: once an operation has started, it will run to the end even if nobody needs its result anymore. In 2016 Domenic Denicola, who had explained what promises are for, proposed adding cancellable promises to the language. Half a year later, in December, the proposal was withdrawn. The author wrote only that he could not continue the work because of internal circumstances at Google, and nobody ever learned the details. Later the committee came back to cancellation in a different form, but that proposal has not become part of the language either.

In the end, cancellation came from the browser. To abort network requests, the DOM standard added AbortController: an object with a signal that can be passed to any function and later triggered to tell it that it is time to stop. Node eventually adopted the same construct. It works, but only if the signal is passed by hand into every function along the whole chain and every function checks it.

What happens if this is not done is shown by the experiment in experiments/11-time. A slow operation writes a record to the database after half a second. The calling code is prepared to wait no more than a hundred milliseconds, and the first variant does it in the most common way, through Promise.race with a timer:

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