Experiment #1: Can JavaScript run something like a concurrent thread/process? No.

So, I know it is stated frequently that JavaScript is "a single-threaded" language. But it is non-blocking thanks to Web APIs.

However, I was thinking whether it means that we can run something concurrently like in some other languages like Java, Go, or Python. I mean ES6 includes Promises and it was enhanced by async-await. So, is it possible to make use of Promises to run multiple things in the same time?

It was fairly a simple experiment. All you need is

  1. A function that acts as a Promise (an async function),
  2. A method that will be run as a Promise and as a synchronous function, and
  3. A "container" function that holds both async function and plain function.

With that three method in mind, this is the code that I came up with.

function timelapse(id) {
  for (let i = 1; i <= 1_000_000; i++) {
    if (i % 500_000 === 0) {
            console.log(`${new Date().getTime()} ${id}`);
        }
  }
}

async function asyncFunction(id) {
  timelapse(id);
}

const experiment = async () => {
  asyncFunction(1);
  asyncFunction(2);

  timelapse(0);
}

experiment()

It's quite straightforward. There is a time lapse function as the process that we want to see running. The long loop is to make sure that the printing of time is not too frequent and the gap between time (and hopefully, between ids) can be seen.

If you tried running the code, you can see that the result is always is in order: from 1, then 2, and last 0. I thought that asyncFunctions would be running asynchronously along side timelapse(0) but it seems not.

However, there is something interesting about the result. (Here is an example if you haven't tried running it yourself)

1638284587975 1
1638284587991 1
1638284587994 2
1638284587995 2
1638284588001 0
1638284588002 0

It seems that the difference of time of id 1 is consistently larger than compared to id 2 and id 0. I am not sure why though.

(Ha, I am not even sure if it only happens on my setup. Maybe this needs to be run on a different setup to know whether it is my environment that affects it or not.)

That's it! So in conclusion, JavaScript's Promise cannot substitute a true asynchronous capabilities like Java's thread or Go's goroutine.

Comments

Popular posts from this blog

Ruby on Rails Time, Date, DateTime Cheatsheet

SQL WHERE and HAVING clause (with examples)