As I have understood so far: Javascript is single threaded. If you defer the execution of some procedure, you just schedule it (queue it) to be run next time the thread is free. But Async.js defines two methods: Async::parallel & Async::parallelLimit
, and I quote:
Run an array of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback...
The same as parallel only the tasks are executed in parallel with a maximum of "limit" tasks executing at any time.
As far as to my understanding of English, when you say: "doing tasks in parallel" means doing them at the same time - simultaneously.
How may Async.js execute tasks in parallel in a single thread? Am I missing something.
How may Async.js execute tasks in parallel in a single thread? Am I missing something.
parallel
runs all its tasks simultaneously. So if your tasks contain I/O calls (e.g. querying DB), they'll appear as if they've been processed in parallel.
how is this enabled in a single thread?! that is what I could not make sense of.
Node.js is non-blocking. So instead of handling all tasks in parallel, it switches from one task to another. So when the first task makes I/O call making itself idle, Node.js simply switches to processing another one.
I/O tasks spent most of its processing time waiting for the result of the I/O call. In blocking languages like Java, such a task blocks its thread while it waits for the results. But Node.js utilizes it's time to process another tasks instead of waiting.
so that means that if the inner processing of each task is asynchronous the thread is granted to each bit of this tasks regardless if anyone of them has finished or not until all have finished their bits?
Yes, it's almost as you said. Node.js starts processing the first task until it pauses to do an I/O call. At that moment, Node.js leaves it and grants its main thread to another task. So you may say that the thread is granted to each active task in turn.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With