0

(First off, please read carefully: I understand asynchronous programming and I've done my homework. This isn't a "how do you use callbacks?" question.)

I'm working on a Javascript re-implementation of an existing software tool that was written in a synchronous/blocking I/O paradigm. Unfortunately, it involves a lot of recursive parsing that can unpredictably lead to I/O requests. So there are certain functions that I'd really, really like to just spin while the I/O happens. That is, I want to write something like this:

function super_duper_nested () {
     ... oh crap I need to wait for an I/O result

     while (runtime.eventsPending ())
         runtime.processEvents ()

     ... grab result and continue
}

But, as far as I can tell, this just isn't available in standard Javascript environments. Is that really the case? Are there any sneaky ways to pause my control flow and let events get processed for a bit?

I've read some things about "synchronous events" in browsers that seem relevant, but my impression is that it's unlikely that I can wire them into this complicated application in a sane way.

Finally, Firefox does appear to have a DebuggerServer.xpcInspector.enterNestedEventLoop interface that might do exactly what I want. But with a name like that, it is not something that I'm willing to embed in production code. (Besides the whole thing of wanting my code to work on platforms other than Firefox.)

Peter
  • 349
  • 2
  • 7
  • from what I can understatnd... what you are asking is not possible... since javascript(browser) runs in a single thread if your script keeps a wait state then the browser tab will be in a hung state... – Arun P Johny Sep 24 '14 at 04:06
  • @ArunPJohny Well, with a `while (true) {}` loop, yes, that would be the case. But many other event-loop systems provide a function that you can call to pump the event loop in a nested manner ([e.g., Gtk](https://developer.gnome.org/gtk3/stable/gtk3-General.html#gtk-events-pending)). The function has to be somewhat magical on the runtime side, but it can be totally compatible with a single-threaded model. – Peter Sep 24 '14 at 04:13
  • What about [Promises](https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise)? – Martin Ernst Sep 24 '14 at 09:03
  • @MartinErnst They don't help in this case. They provide a nice way of dealing with asynchronous events, but still involve callbacks and a need to escape to the main event loop to process those events. – Peter Sep 24 '14 at 12:59
  • Some relevant related questions, with answers that are not encouraging for there being a way to do this: [8565638](http://stackoverflow.com/questions/8565638/getting-synchronous-behavior-in-javascript), [23834404](http://stackoverflow.com/questions/23834404/hacks-to-make-synchronous-javascript-calls). – Peter Sep 24 '14 at 23:44

0 Answers0