Aside from using a different scripting language, it seems that the main appeal of node.js is it's support for event-driven programming which makes it easier to write scalable servers (or other typically I/O bound applications) due to its simplified non-blocking I/O calls. However, this feature comes at the expense of having to learn a new programming model which essentially requires you to pass callback after callback function making some straightforward tasks (e.g. dependent sequences of actions) a bit more complicated.
Contrast that programming model to the traditional one of Ruby on Rails which blocks on all I/O operations and is (effectively) single-threaded (due to MRI's green thread implementation).
Just dreaming out loud here, it seems that it should be possible to implement a Ruby (or Rails) runtime which reconciles these models by trapping I/O calls, transparently replacing them with their non-blocking version, storing the current continuation and calling it when the I/O operation is complete. This way you would get the familiar, procedural pr开发者_C百科ogramming style and the benefits of the event-driven/asynchronous/callback model.
Is such a runtime (or runtime translator) technically possible? Are there web frameworks that do something like this already?
Yes.
There are two possibilities for doing asynchronous but imperative programming
Use a real asynchronous language:
Erlang would be an example where you can write imperative do this, do that code and it translates to async. I don't think it goes all the way though.
Use a compiler
You can use a compiler that converts blocking style code into non-blocking code. I personally highly recommend against this because it's a black box and a nightmare to debug.
One example would be storm
However, this feature comes at the expense of having to learn a new programming model which essentially requires you to pass callback after callback function making some straightforward tasks (e.g. dependent sequences of actions) a bit more complicated.
I however recommend that you bite the bullet and make the paradigm switch. This will be a far better investment in the long-run. Mind you it's not neccessary to use node.js, there are strong alternatives like erlang and haskell out there.
Thanks to @igorw, the async-rails project is what I was imagining.
But as @Raynos and @apneadiving point out, there are potentially better solutions such as Ruby EventMachine and stormjs.
精彩评论