javascript-tutorials/asynchronous_programming/README.md

53 lines
2.2 KiB
Markdown
Raw Normal View History

2024-08-07 10:21:34 +02:00
# Asynchronous JavaScript
JavaScript is single-threaded but it can still take advantage of asynchronous
programming.
When we say JavaScript is single-threaded, we mean that we cannot write
2024-08-07 11:57:28 +02:00
multithread/concurrent code without using JavaScript APIs. In fact,
2024-08-07 10:21:34 +02:00
despite for us it appears single-threaded, it takes advantage of the
`libuv` library, allowing the engine to be effectively multithread.
2024-08-07 11:57:28 +02:00
Another way to put it is that we have one and only one Call Stack.
2024-08-07 10:21:34 +02:00
In order to do that, JavaScript uses
* The libuv APIs which allow multithreading
* The Event Loop Queue
## Explaination
JavaScript provides a set of APIs, including `setTimeout` and `fetch`, which
are offloaded to the libuv library when called. The libuv library handles the
2024-08-07 10:25:06 +02:00
underlying operations, such as timer management and HTTP requests, respectively.
While `libuv` performs these operations, our JavaScript code continues its
execution, without being blocked. That's why we said that the engine is
multithreaded.
2024-08-07 10:21:34 +02:00
2024-08-07 10:25:06 +02:00
Both `setTimeout` and `fetch` have associated functions, known as callbacks, that
are executed once the operation has completed.
2024-08-07 10:21:34 +02:00
Since the engine cannot directly push these callback functions onto the call stack
without disrupting the current flow of execution, it instead places them in a
queue called the "Event Loop Queue". When the call stack is empty, the engine
checks the queue and, if there are any pending callbacks, proceeds to execute them.
**Example**
```javascript
setTimeout(() => console.log('I will go in the event loop queue first'), 1000);
console.log('I am in the stack');
```
What is happening here? `setTimeout` is a JavaScript API which will be taken care
2024-08-07 10:25:06 +02:00
of by the `libuv` library which will be responsible for checking when 1000ms have passed.
2024-08-19 11:43:27 +02:00
**Concurrently**, the engine executes
2024-08-07 10:21:34 +02:00
`console.log('I am in the stack');`.
When 1000ms have elapsed, the callback function associated with the timer (console.log)
gets enqueued in the Queue.
Since there is nothing to do in the stack, the callback pushes the callback onto the
2024-08-07 11:57:28 +02:00
stack and executes it.
## Useful resources
* https://www.youtube.com/watch?v=lqLSNG_79lI
* https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif
2024-08-19 11:43:27 +02:00
* https://www.youtube.com/watch?v=eiC58R16hb8