2

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
  • 6
    What's your ultimate goal? Please read How to Ask. Commented Oct 10, 2017 at 5:52

1 Answer 1

3

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:

  1. Use operations that are already asynchronous (such as fs.readFile() or http.get()).
  2. 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.
  3. 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.

Sign up to request clarification or add additional context in comments.

4 Comments

As You mentioned 3 ways to write code that is asynchronous,First one is I know how to use.I would like to know about 2nd and 3rd ways to make code asynchronous with simple example. Thanks
@Dnyanesh - 2nd way (native code add-on) is documented here. 3rd way (child process) is documented in the child_process module. Child processes are regularly used in node.js to off-load CPU-intensive stuff (image processing, heavy calculations, etc...) from the main node.js thread. Often one will create a number of child process "workers " and then create a work queue to manage work that is handed off to the workers.
I gone through given documentation for 2nd way.If I create function(like addition,subtraction) using Addons then I am calling of that functions, in that case function's execution will be Asynchronous or Synchronous ?
@Dnyanesh - Unless your add-on uses threads or some other process or some naturally async OS function and exposes an async interface to the Javascript, it will still be synchronous. You have to write the native code to be async.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.