I have two functions, first function perform simple addition and second one is performing subtraction. How will these functions can execute asynchronously in Node.JS ?
1 Answer
I have two functions, first function perform simple addition and second one is performing subtraction. How will these functions can execute asynchronously in Node.JS ?
In short, you can't. You can't make synchronous code run truly asynchronously within your node.js process. You can affect the timing (like starting it with a setTimeout() sometime in the future), but when it runs it will still be synchronous, not asynchronous.
The only ways to write new code that is asynchronous are:
- Use operations that are already asynchronous (such as
fs.readFile()orhttp.get()). - Write your own native code with an asynchronous interface in a node.js add-on. You can then use actual system threads or non-blocking system interfaces to implement your code if necessary.
- Move the javascript code to another node.js process that you run as a child and communicate back the result. Then, your node.js process can run independently of the child node.js process providing an asynchronous interface.
Only native code or node.js functions that are backed with native code or other processes can be truly asynchronous in node.js. You can't take plain Javascript code (such as your addition and subtraction functions and turn them from synchronous to asynchronous within your single node.js process. There is no magic way to do that. By definition, node.js runs all your Javascript in a single thread.