Synchrously execute any async function by blocking in a worker
Sometime you have to work with generated code that expects a synchronous delegate, and you don't want to mess with the compiler (e.g. an Emscripten file system).
We've always had a synchronous function via XMLHttpRequests. This wasn't useful for making arbitrary async functions synchronous because it could only get results from a server. However, now Service Workers allow us to intercept network calls. We use this to intercept and route synchronous xhr calls from a worker, and block until the the function completes.
- Run a static webserver and open
index.html
(likepython -m SimpleHTTPServer
)
- As implemented blocking calls can only be made from a Web Worker
- Only works in Chrome and Firefox
TC39 introduced SharedArrayBuffers and Atomics. Now we can pre-allocate a buffer and share the same one between the (ui thread?) and a web worker. Using Atomics' wake
and wait
, we can block in the worker and signal from UI. We can also communicate back to the worker using the same buffer.
- Get latest Chrome Canary
- Go to
chrome://flags
- Enable "Experimental enabled SharedArrayBuffer support in JavaScript" (search for
#shared-array-buffer
) - Run a static webserver and open
index.html
(likepython -m SimpleHTTPServer
)
- Only works in Chrome Canary