Proposal: JS Synchronize Execute Promise

I would like to state one point of my confusion. Why JS cannot achieve synchronous waiting for asynchronous results. Sometimes we need to introduce a new asynchronous API. In some cases, we cannot change this API to synchronous. And we need to ensure that the method is executed sequentially. For asynchronous methods, this is very simple, just use await. But if the caller is a synchronous method, we need to change it to asynchronous. If this is done, it will disrupt the execution order of existing methods. Can JS achieve synchronous waiting for return results. Similar to Task. result in C #, it blocks and waits for the obtained result to be executed.

Hi @SNFS

On one hand there are ways to wait synchronously such as: Atomics.wait() - JavaScript | MDN

However blocking the thread like this is only permitted if the host allows it. In Web Browsers this API is only allowed in worker threads, and not the main thread. This is because if the main thread is blocked then the entire website will freeze, the user wouldn't be able to click a 'cancel' button for example.

Another aspect to this is that JavaScript has run to completion semantics

"This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be preempted and will run entirely before any other code runs (and can modify data the function manipulates)"

2 Likes