Home > Software engineering >  Writing custom, true Asynchronous functions in Javascript/Node
Writing custom, true Asynchronous functions in Javascript/Node

Time:11-24

  1. How do the NodeJS built in functions achieve their asynchronicity?

  2. Am I able to write my own custom asynchronous functions that execute outside of the main thread? Or do I have to leverage the built in functions?

CodePudding user response:

Javascript is mono-thread, if you want to create 'thread' you can use https://nodejs.org/api/worker_threads.html.

But you may have heard about async function and promises in javascript, async function return a promise by default and promise are NOT thread. You can create async function like this :

async function toto() {
  return 0;
}

toto().then((d) => console.log(d));
console.log('hello');

Here you will display hello then 0 but remember that even the .then() will be executed after it's a promise so that not running in parallel, it will just be executed later.

CodePudding user response:

Just a side note, true asynchronous doesn't really mean anything. But we can assume you mean parallelism?.

Now depending on what your doing, you might find there is little to no benefit in using threads in node. Take for example: nodes file system, as long as you don't use the sync versions, it's going to automatically run multiple requests in parallel, because node is just going to pass these requests to worker threads.

It's the reason when people say Node is single threaded, it's actually incorrect, it's just the JS engine that is. You can even prove this by looking at the number of threads a nodeJs process takes using your process monitor of choice.

So then you might ask, so why do we have worker threads in node?. Well the V8 JS engine that node uses is pretty fast these days, so lets say you wanted to calculate PI to a million digits using JS, you could do this in the main thread without blocking. But it would be a shame not to use those extra CPU cores that modern PC's have and keep the main thread doing other things while PI is been calculated inside another thread.

So what about File IO in node, would this benefit been in a worker thread?.. Well this depends on what you do with the result of the file-io, if you was just reading and then writing blocks of data, then no there would be no benefit, but if say you was reading a file and then doing some heavy calculations on these files with Javascript (eg. some custom image compression etc), then again a worker thread would help.

So in a nutshell, worker threads are great when you need to use Javascript for some heavy calculations, using them for just simple IO may in fact slow things down, due to IPC overheads.

You don't mention in your question what your trying to run in parallel, so it's hard to say if doing so would be of benefit.

  • Related