问题
JavaScript uses asynchronous calls in most of the modern APIs dealing with "slow" things like disk IO and network. I realize what the purpose of this, however there are certain cases when making synchronous calls really needed.
For example, I have a JavaScript code that I can't rewrite. In the code there are synchronous call to a certain method. For some debugging purposes at developer's environment I want to intercept this call, send information to server and wait until server responds. This interceptor won't work on production. AFAIK, there was a way to do this with NPAPI, but now it is officially deprecated. And both Google Chrome and Mozilla Firefox provide only asynchronous socket API, so I have no chance to perform such interception. Another way is to send syncrhonous XMLHttpRequest, but is is considerably slow, at is requires HTTP connection and HTTP payload, so I would prefer WebSocket.
I have another corner case where I have to call IndexedDB, but it is very hard to explain. Unfortunately IndexedDB sync API is not implemented anywhere.
Are there another hacks to call asynchronous methods synchronously? I would accept browser-specific hacks, browser add-ons, plugins and so forth. Or may be someone knows how to ask all those committees (and browser developers as well) that develop Web standards to include at least WebWorker versions of syncrhonous API?
I know, that questions about calling asynchronous method synchronously were asked many times, and the common answer is "this is a bad idea". I realize that generally it is a bad idea, but in a certain cases we really need freedom to call synchronously.
回答1:
I don't know of any way. I usually describe asynchronous code as viral: it quickly infects the code around it with more asynchronicity. I don't know any way to break that, and it seems unlikely to me that there is a way. Obviously there are techniques to make your asynchronous code look more synchronous, starting with Promises, and continuing into macros and such. But in the end, the runtime is still asynchronous.
Maybe someone smarter than me can provide an interesting suggestion. I'd love to hear it too, although I don't have any personal need at the moment.
回答2:
Some other ideas that you might want to consider:
For the web based traffic
Use a proxy server to intercept the communication. I found an article here that discusses using a proxy server with web sockets. A properly written proxy could hold onto the transferred data until its exchange with the server was complete, then pass things forward.
For the IndexedDb
You could create a wrapper function around the IndexedDb calls, or at least the ones you needed, that would allow you to interject whatever behavior you needed in. This wrapper could modify data and perform its own async business before invoking the callback method.
来源:https://stackoverflow.com/questions/23834404/hacks-to-make-synchronous-javascript-calls