February 12, 2024
V8, Libuv, and Async in JavaScript
JavaScript is a Synchronous language
JavaScript is a compiled language and is executed by the V8 engine.
V8 Engine
- Developed by Google (comparable to Chakra by Microsoft).
- V8 - A JavaScript Engine for Both Client-Side and Server-Side Execution
- Compiles JavaScript directly into native machine (byte) code before execution.
- Optimizes JavaScript code for improved performance.
- Utilizes caches to enhance execution speed.
- Asynchronous operations are handled by the Event Loop, libuv in Node.js, and web APIs in browsers.
V8 Engine and Handling Asynchronous Operations
- V8 itself does not directly handle asynchronous operations.
- Instead, it integrates with the Event Loop.
- The Event Loop allows JavaScript code to perform non-blocking operations by executing async tasks.
- V8 works alongside the Libuv library, which provides support for asynchronous I/O-based operations.
- Input/Output operations are processed between Node.js and Network/Disk/DB
- V8 supports modern JavaScript features such as Promises and the async/await syntax.
- It optimizes asynchronous code execution through just-in-time (JIT) compilation and other optimization strategies.
Libuv library in JavaScript Allows
- Async TCP and UDP sockets
- Async DNS (c-ares IPv6)
- Async filesystem events
- Child processes
- Thread pool
Event Loop
- The entity that handles external events and converts them into callback invocations.
- A loop that retrieves events from the queue and pushes these callbacks to the call stack.
Async Function
- Async fun that returns Promise.resolve
- Call this fun will return Promise
❌ Promise Hell
We can see the problem when we have multiple requests that rely on each other.
Example with Promise
- ❌ Difficult to read
- ❌ Difficult to understand what is happening
- ✅ in this case better to use async/await
Example with Async/Await
- Execution pauses at the line
await getUser()
until the promise resolves.
- While waiting, Synchronous Code outside of the async function continues to run.
- Once the promise is resolved, execution of the code following
await getUser()
resumes.
Example Object methods with Async/Await
- ✅ Using chaining for fetching data offers clearer workflow management.
- ✅ This approach is particularly useful when one response depends on another.
Multiple calls
await/await + Error Handler try catch