Why is there no synchronous WebSocket support in Web Workers when there is synchronous FileSystem support?

Janus Troelsen picture Janus Troelsen · Sep 27, 2012 · Viewed 7.4k times · Source

I understand why browser vendors don't want to help me block their UI thread. However, I don't understand why there is:

  1. no sleep(2) in Web Workers
  2. no synchronous WebSockets API

There is a synchronous FileSystem API. There is also a synchronous IndexedDB API. To me, it seems like a contradiction.

Answer

saml picture saml · Oct 5, 2012

The reason why there's not a sleep() function available to WebWorkers is simple: you don't need it. sleep is a synchronous function, (it blocks until it returns) which doesn't make sense in the asynchronous context of WebWorkers.

If you send a message to a WebWorker, it doesn't block waiting for a response; the response is sent as a message to your message handler function. If you want to wait a certain amount of time before sending a response, you wouldn't use sleep, you'd use setTimeout and fire a message off when your function gets called.

Similarly, if you're using WebWorkers for WebSocket data transmission, you'd receive a message from the main thread, send a packet via websocket asynchronously, then in the response handler you'd send a message back to the main thread. There's no logical place to use a synchronous sleep function.

As far as why there's not a synchronous mode for WebSockets like there is for the filesystem, the primary difference is that the filesystem isn't accessed across the network. Generally, asynchronous APIs are preferable for network-based functions, so I guess I don't see it as much of a contradiction.

IDB is only supported by 3 browsers, none of which have implemented the synchronous API, so I don't see that as a shining example of synchronous APIs. Inf fact, I think that's the contradiction that people would define an API and not bother to implement it.