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:
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