Is there any way to create threads for running multiple methods at a time?

That way, if any method fails in between all the other threads should be killed.


Solution 1:

New answer: While node.js didn't used to have the ability to use threading natively, the ability has since been added. See https://nodejs.org/api/worker_threads.html for details.

Old answer: Every node.js process is single threaded by design. Therefore to get multiple threads, you have to have multiple processes (As some other posters have pointed out, there are also libraries you can link to that will give you the ability to work with threads in Node, but no such capability exists without those libraries. See answer by Shawn Vincent referencing https://github.com/audreyt/node-webworker-threads)

You can start child processes from your main process as shown here in the node.js documentation: http://nodejs.org/api/child_process.html. The examples are pretty good on this page and are pretty straight forward.

Your parent process can then watch for the close event on any process it started and then could force close the other processes you started to achieve the type of one fail all stop strategy you are talking about.

Also see: Node.js on multi-core machines

Solution 2:

There is also at least one library for doing native threading from within Node.js: node-webworker-threads

https://github.com/audreyt/node-webworker-threads

This basically implements the Web Worker browser API for node.js.

Solution 3:

Update 2:

Since Node.js 12 LTS Worker threads are stable.


Update 1:

From Node v11.7.0 onward, you do not have to use --experimental-worker flag.

Release note: https://nodejs.org/en/blog/release/v11.7.0/


From Node 10.5 there is now multi threading support, but it is experimental. Hope this will become stable soon.

Checkout following resources :

Solution 4:

You can get multi-threading using Napa.js.

https://github.com/Microsoft/napajs

"Napa.js is a multi-threaded JavaScript runtime built on V8, which was originally designed to develop highly iterative services with non-compromised performance in Bing. As it evolves, we find it useful to complement Node.js in CPU-bound tasks, with the capability of executing JavaScript in multiple V8 isolates and communicating between them. Napa.js is exposed as a Node.js module, while it can also be embedded in a host process without Node.js dependency."