Comment

Comment by ermir

I tried this exact thing last year, and it does not work for a particular reason: the JavaScript event loop guarantees that a function will run to the end before any callbacks will run, but an await is an implicit callback (a Promise under the hood). This means that you break the guarantee that variables or other memory locations will have the same value between statements.

This is exactly the same problem that languages such as C++ have when dealing with multithreading, and why constructs such as semaphores, mutexes, etc. exist. JS does not have these, and using the technique in the article will completely break the language.

Compare these two fiddles I prepared and see for yourself:

This one uses await to block for a second, which in the meantime changes the value of the variable between statements: https://jsfiddle.net/gq1btLdu/

This one uses a for loop to do synchronous work for about a second, then prints the initial value twice. You will notice that the setInterval never had the chance to run, since callbacks are scheduled to run only once the current function ends: https://jsfiddle.net/gq1btLdu/1/

parent ermir 5 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton