Javascript Promises in depth with V8 engine internals

server side digest - Sep 9 - - Dev Community

๐Ÿ˜… Being a single threaded language most of the people think that Javascript or NodeJS is slow and not scalable. Python and JS be like:-

Javascript Python meme

Well, it depends. If your service is I/O (input output like file reading, DB call, Http call etc) heavy which means it has dependency on other resource being read or written.

โšก๏ธ There, NodeJS performs good as compared to other stacks in general when your service is IO heavy instead of CPU heavy.

โ“ This is because NodeJS or JS has something like handing over its work to the underlying thread of the Operating system to carry out IO execution.

It passes the callback (a function) to that thread and continue with the execution of other instructions in the code, which is called async programming also in fancy terms.

Well Well Well, Let's take a step back and understand what we wrote above:-

Blocking nature of JS

JS blocking nature

  • Javascript is a single threaded language and hence can work on one task at a time unlike Java where multiple threads are present to handle workload in parallel (multithreading).
  • So, if one function/instruction is running, next instruction will wait for this instruction to get completed and we can't run them in parallel.

Let's see how one instruction blocks another one:-

Step 1 of blocking nature of js

Step 2 of blocking nature of js

Step 3 of blocking nature of js

Step 4 of blocking nature of js

โœ… You can refer video explanation (in english) with code examples and v8-engine internals here:- https://www.youtube.com/watch?v=JN89L2SqPA8

Non blocking nature

Now, in JS runtime environment (NodeJS) we have some C++ APIs that have some functions like setTimeout, Promises, localStorage which are executed by the threads of our Operating systems, not by the main JS thread.

You can see the right box having C++ APIs here:-

C++ Nodejs APIs

  • Whenever, we perform IO through any C++ API like executing a promise , performing HTTP call or DB operation etc JS main thread hands over the main work to the OS thread and the main thread of JS continues working on other code and doesn't wait for the Async code to run.
  • It provides a callback (a function) to execute when call stack gets empty (call stack has only the sync code and async code goes to microtask or task queue)
  • Event loop, loops through these queues when call stack gets empty & put the callbacks from these queues to the main stack and returns the result.

Promise execution in task queue

setTimeout execution

For more in depth details of How promises are implemented in C++ code, refer this:- https://www.youtube.com/watch?v=JN89L2SqPA8


๐Ÿ”ฅ Follow for more such articles...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player