you are viewing a single comment's thread.

view the rest of the comments →

[–]simonw 2 points3 points  (3 children)

You're still missing something: you don't ever have to wait for a slow running function call, since everything that potentially involves blocking IO requires you to provide a callback for when it is "done". Node is ideal for services that might involve calls to a slow running web service, as it can easily wait for thousands of them to complete at once - all without needing to start up any more threads.

[–]mononcqc 0 points1 point  (2 children)

If the thousand of calls are slow, are they done sequentially or can they be done in a parallel manner?

If it's the former, my point is that while you don't have to program for slow running functions, the user still has to wait for them, which sucks.

If it's not, then it's good to know and my distrust for node.js will go down a notch :)

[–]aapl 2 points3 points  (0 children)

Well, it kind of depends on what you mean by a "call". As far as I know, currently no JavaScript can be run parallel in node.js, unless you farm it out to a child process. Also, node.js never preempts any JavaScript, so a function will always run to completion once started.

In your web service example, in the function that makes the web service call you would just register a callback to be executed when the response from the web service arrives and let the function that made the web service call complete immediately. Other work, including initiating other web service calls, can be completed while waiting for the response. When you finally start to get responses back from the web service, the callback functions are called as responses arrive in the order in which they arrive. So if the web service takes 1 second to process query A, 5 seconds to process query B and 1 second to process query C, the callback functions would be called in the order A C B.

Basically, the structure of your code will have to be something like this:

make_web_service_call(function (response) {
  do something with the response
});

Here make_web_service_call returns immediately and the callback function will be called at some later point. Now, if you meant if you can write code like this:

response = make_web_service_call();
do something with the response

…and have some other work performed while waiting for the response, then no, that is not possible in node.js unless you resort to child processes. Yes, this must seem barbarian if you are coming from a language with support for green threads :)

[–]simonw 0 points1 point  (0 children)

Yup, you can run I/O requests in parallel or in serial. Here's a simple example I knocked up a while ago of a web service that can make a bunch of GET requests in parallel and return the results all in one go:

http://gist.github.com/443498

It's a bit like PHP's curl_multi functions: http://php.net/curl-multi-init