javascript-tutorials/asynchronous_programming
xfarrow 374f29c955 renaming folder 2024-08-19 16:44:24 +02:00
..
0_callbacks.js renaming folder 2024-08-19 16:44:24 +02:00
1_promises.js renaming folder 2024-08-19 16:44:24 +02:00
2_promise-chaining.js renaming folder 2024-08-19 16:44:24 +02:00
3_async-await.js renaming folder 2024-08-19 16:44:24 +02:00
README.md renaming folder 2024-08-19 16:44:24 +02:00
sincrono_vs_asincrono.txt renaming folder 2024-08-19 16:44:24 +02:00

README.md

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 multithread/concurrent code without using JavaScript APIs. In fact, despite for us it appears single-threaded, it takes advantage of the libuv library, allowing the engine to be effectively multithread.

Another way to put it is that we have one and only one Call Stack.

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 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.

Both setTimeout and fetch have associated functions, known as callbacks, that are executed once the operation has completed. 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

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 of by the libuv library which will be responsible for checking when 1000ms have passed. Concurrently, the engine executes 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 stack and executes it.

Useful resources