Skip to content

Commit e5cdccc

Browse files
committed
Event Loop in Node
1 parent 77b84fd commit e5cdccc

31 files changed

+134
-55
lines changed

Javascript/js-basics/Closure/closure-setTimeout-GOOD-REFERENCE.js renamed to Javascript/js-basics/Closure/closure-setTimeout-MOST-POPULAR.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -66,5 +66,7 @@ setTimeout's job, when called, is to immediately set a timer that will expire af
6666
6767
setTimeout does not wait for the time interval to expire and then execute. setTimeout executes immediately. It is the callback function in setTimeout's first argument that waits/executes.
6868
69-
Further Reading - https://medium.freecodecamp.org/3-questions-to-watch-out-for-in-a-javascript-interview-725012834ccb
69+
Further Reading -
70+
1. https://medium.freecodecamp.org/3-questions-to-watch-out-for-in-a-javascript-interview-725012834ccb
71+
7072
*/

Javascript/js-basics/Closure/closure-tricky-GREAT-EXAMPLE.JS

+2
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ logText();
2323
/* When I run the above code, the first < console.log(text) > will print 'undefined' instead of 'outside' - Here's Why - when I have the variable 'text' declared and assigned both inside the function and outside the function -
2424
https://medium.com/backticks-tildes/understanding-hoisting-and-scoping-in-javascript-39ea7b41e31
2525
26+
Variable Shadowing -
27+
2628
In JavaScript, variables with the same name can be specified at multiple layers of nested scope. In such case local variables gain priority over global variables. If you declare a local variable and a global variable with the same name, the local variable will take precedence when you use it inside a function. This type of behavior is called shadowing. Simply put, the inner variable shadows the outer. This is how the Javascript interpreter finds a particular variable; it searches for the variable at the innermost scope being executed at the time, and continues until the first match is found, even if there are other variables with the same name in the outer scope.
2729
2830
So in above, it takes the 'text' declared inside the inside the function, but then only variable declaration is hoisted and NOT variable-assignment. So here, I am trying to print the 'outside' variable before assigning a value to it. So it prints undefined.
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
/* call() and apply() methods with the same use case like the other file
22
This time there is a car object without the displayDetails function, which is located in the globa */
33

4-
54
var car = {
6-
regNo : 'GA123',
7-
brand: 'Ford',
8-
}
5+
regNo: "GA123",
6+
brand: "Ford"
7+
};
98

10-
function displayDetails (ownerName) {
11-
console.log(`${ownerName}, this is your car : ${this.regNo} ${this.brand}`);
9+
function displayDetails(ownerName) {
10+
console.log(`${ownerName}, this is your car : ${this.regNo} ${this.brand}`);
1211
}
1312

1413
displayDetails.apply(car, ["Paul"]);
@@ -23,4 +22,4 @@ arrow functions) doesn't create new functional context and use context of a call
2322
2423
*/
2524

26-
displayDetails.call(car, "Steve");
25+
displayDetails.call(car, "Steve");
+26-30
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,48 @@
11
//Example -1 super simple example of custom callback. done() is a callback which I am definining seperately.
22
done = () => {
3-
console.log("Done from Callback");
4-
}
3+
console.log("Done from Callback");
4+
};
55

66
printNum = (num, callback) => {
7+
for (let i = 0; i <= num; i++) {
8+
console.log(i);
9+
}
10+
if (callback && typeof callback === "function") {
11+
callback();
12+
}
13+
};
714

8-
for (let i = 0; i <= num; i++) {
9-
console.log(i);
10-
}
11-
if (callback && typeof(callback) === "function") {
12-
callback()
13-
}
14-
}
15-
16-
// printNum(5, done)
15+
printNum(5, done);
1716

1817
// Example-2, where, I will pass the callback after invoking the function, without defining the callback separately
1918
mySandwitch = (a, b, callback) => {
20-
21-
console.log(`Started eating my sandwitch.\n\nIt has: ${a} and ${b}`);
22-
callback()
23-
}
19+
console.log(`Started eating my sandwitch.\n\nIt has: ${a} and ${b}`);
20+
callback();
21+
};
2422

2523
/*mySandwitch('cheese', 'ham', () => {
2624
console.log('Finished eating my sandwitch');
2725
})*/
2826

2927
// To make the callback optional, we can just do this:
3028
mySandwitchOptional = (a, b, callback) => {
29+
console.log(`Started eating my sandwitch.\n\nIt has: ${a} and ${b}`);
3130

32-
console.log(`Started eating my sandwitch.\n\nIt has: ${a} and ${b}`);
33-
34-
if (callback && typeof(callback) === "function") {
35-
callback()
36-
}
37-
}
31+
if (callback && typeof callback === "function") {
32+
callback();
33+
}
34+
};
3835

3936
/* Write a custom callback function which returns the addition of its 2 arguments through a callback. That, the function would take 2 arguments and the third agument would be a callback function. And the final return output of that function would be with callback. - Was asked in Techolution interview */
4037

41-
addTwoArgs = ( a, b, callback) => {
42-
43-
if (callback && typeof(callback) === 'function') {
44-
return callback()
45-
}
46-
}
38+
addTwoArgs = (a, b, callback) => {
39+
if (callback && typeof callback === "function") {
40+
return callback();
41+
}
42+
};
4743

4844
let result = addTwoArgs(2, 5, () => {
49-
return 2 + 5
50-
})
45+
return 2 + 5;
46+
});
5147

52-
console.log(result);
48+
console.log(result);

Javascript/strict-equality-use-case.js

+15
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,18 @@ console.log('1 == "1" is ', 1 == "1"); // => true
1313
// console.log({0: 1} == {0: 1}); // => false
1414

1515
// console.log({0: 1} === {0: 1}); // => false
16+
17+
/*
18+
Explanation - 1 - Why console.log([1] == [1]); // => false
19+
20+
They are not equal because a new array is being created in each of these statements, each being a brand new array object with just identical contents. If you create two new objects:
21+
22+
var a = {};
23+
var b = {};
24+
25+
a === b // false
26+
27+
When you create new objects, arrays, functions, etc., a brand new object is placed into memory. Creating a new object with the same internals as another object will not magically cause that object to point to one that already exists. The objects may look the same, but they do not point to the same instance.
28+
29+
30+
*/

Javascript/truthy-falsy.js

+8
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,12 @@ null
88
undefined
99
NaN
1010
11+
Everything else is truthy. That includes:
12+
13+
'0' (a string containing a single zero)
14+
'false' (a string containing the text “false”)
15+
[] (an empty array)
16+
{} (an empty object)
17+
function(){} (an “empty” function)
18+
1119
*/

Node-Express/ Asynchronicity-Event-Loop-3.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<img src=" Asynchronicity-Event-Loop.png">
44

5-
Any of the web APIs pushes the callback on to the task queue when it's done. Finally we get to the event loop, title of the talk, what the heck is the event loop is like the simplest little piece in this whole equation, and it has one very simple job. The event loop's job is to look at the stack and look at the task queue. If the stack is empty it takes the first thing on the queue and pushes it on to the stack which effectively run it. So here we can see that now the stack is clear, there's a callback on the task queue, the event loop runs, it says, oh, I get to do something, pushes the callback on to the stack.
5+
The event loop's job is to look at the stack and look at the task queue. If the stack is empty it takes the first thing on the queue and pushes it on to the stack which effectively run it. So here we can see that now the stack is clear, there's a callback on the task queue, the event loop runs, it says, oh, I get to do something, pushes the callback on to the stack.
66

77
- Push main() onto the call stack.
88
- Push console.log() onto the call stack. This then runs right away, and gets popped.

Node-Express/ Asynchronicity-How-Node-handles-concurrency.md

+34-5
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,43 @@
22

33
[The official Doc](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/) has some very good explanation.
44

5-
## 1> Some Key points noted on 10-June-2018 >>
5+
## 1> Some Key points >>
66

77
- A> The simple ans is - With callback function and event-loop
88

9-
- B> With callback function and event-loop, Node transfer execution of the callback function (like, in setTimeout, Promise, fs.readFile) to a queue the output of which follows a FIFO design, while the rest of the code, will get executed. So that’s how its node is non-blocking.
9+
- B> With callback function and event-loop, Node transfer execution of the callback function (like, in setTimeout, Promise, fs.readFile) to a queue the output of which follows a FIFO design, while the rest of the code, will get executed. So that’s how node is non-blocking.
1010

11-
And whatever was transferred to the separate queue for those callbacks will be executed on a FIFO basis, so an the code that was in the queue first, will return its result first. And then the next one in the queue.
11+
And whatever was transferred to the separate queue for those callbacks will be executed on a FIFO basis, so the code that was in the queue first, will return its result first. And then the next one in the queue.
1212

1313
## 2> https://codeburst.io/how-node-js-single-thread-mechanism-work-understanding-event-loop-in-nodejs-230f7440b0ea
1414

15-
Node is single threaded and it is doing magical things with this model. Some of the popular server side technology like PHP, ASP.NET, Ruby & Java Servers all follow Multi-threaded where each client request results in the instantiation of a new thread or even a process, but in Node.js, requests are run on the same thread The main event loop is single-threaded but most of the I/O works run on separate threads, because the I/O APIs in Node.js are asynchronous/non-blocking by design, in order to accommodate the event loop.
15+
Some of the popular server side technology like PHP, ASP.NET, Ruby & Java Servers all follow Multi-threaded where each client request results in the instantiation of a new thread or even a process, but in Node.js, requests are run on the same thread.
16+
17+
##### Misconception 1: The event loop runs in a separate thread than the user code -
18+
Many think, there is a main thread where the JavaScript code of the user (userland code) runs in and another one that runs the event loop. Every time an asynchronous operation takes place, the main thread will hand over the work to the event loop thread and once it is done, the event loop thread will ping the main thread to execute a callback.
19+
20+
#### Reality
21+
**There is only one thread that executes JavaScript code AND ALSO the the event loop. The execution of callbacks (know that every userland code in a running Node.js application is a callback) is done by the event loop.**
22+
23+
24+
### Event Loop vs Worker Pool (Thread Pool)
25+
26+
[https://nodejs.org/ja/docs/guides/dont-block-the-event-loop/(https://nodejs.org/ja/docs/guides/dont-block-the-event-loop/)
27+
28+
Node uses a small number of threads to handle many clients. In Node there are two types of threads: one Event Loop (aka the main loop, main thread, event thread, etc.), and a pool of k Workers in a Worker Pool (aka the threadpool). Node uses the Event-Driven Architecture: it has an Event Loop for orchestration and a Worker Pool for expensive tasks.
29+
Event Loop executes the JavaScript callbacks registered for events, and is also responsible for fulfilling non-blocking asynchronous requests like network I/O.
30+
31+
#### What code runs on the Worker Pool?
32+
33+
Node's Worker Pool is implemented in libuv (docs), which exposes a general task submission API.
34+
35+
Node uses the Worker Pool to handle "expensive" tasks. This includes I/O for which an operating system does not provide a non-blocking version, as well as particularly CPU-intensive tasks.
36+
37+
Event loop is the mechanism that takes callbacks (functions) and registers them to be executed at some point in the future. It operates in the same thread as the proper JavaScript code. When a JavaScript operation blocks the thread, the event loop is blocked as well.
38+
39+
Worker pool is an execution model that spawns and handles separate threads, which then synchronously perform the task and return the result to the event loop. The event loop then executes the provided callback with said result.
40+
41+
===============================
1642

1743
## 3> Single Threaded Event Loop Model Processing Steps:
1844

@@ -131,4 +157,7 @@ Node has a pool of Thread and you must be scratching your head wondering if Node
131157

132158
Generally the web server and the database server are 2 different machines, because of Async nature, the event loop gets free after forwarding the read/write request to database server. That is why, a Node JS HTTP server can handle a large number of requests while the process of complex read/write operations could be inprocess on database server(s).
133159

134-
### Further Resources - https://youtu.be/8aGhZQkoFbQ - Very famous video
160+
###
161+
162+
- 1. Further Resources - https://youtu.be/8aGhZQkoFbQ - Very famous video
163+
- 2. [https://nodejs.org/ja/docs/guides/dont-block-the-event-loop/](https://nodejs.org/ja/docs/guides/dont-block-the-event-loop/)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
**JavaScript is single threaded, that means only one statement is executed at a time. As the JS engine processes our script line by line, it uses this single Call-Stack to keep track of codes that are supposed to run in their respective order.**
2+
3+
Like what a stack does, a data structure which records lines of executable instructions and executes them in LIFO manner. So say if the engine steps into a function foo(){ it PUSH-es foo() into the stack and when the execution of foo()return; } is over foo() is POP-ped out of the call-stack.
4+
5+
<img src="./sequential-execution-1.png">
6+
7+
EXERCISE 1: So from the above diagram shows how a typical line by line execution happens. When the script of three console.log() statements is thrown at JS — 
8+
9+
- Step 1: The console.log("Print 1") is pushed into the call stack and executed, once done with execution, it is then popped out of the stack. Now the stack is empty and ready for any next instruction to be executed.
10+
11+
- Step 2: console.log("Print 2"); // is the next instruction is pushed and the same thing repeats until
12+
13+
- Step 3: is executed and there is nothing left to push and execute.
14+
15+
Lets take an example to understand it better, its a famous Interview question as well. In the logText() function, I am only doing console.log() three times.
16+
17+
```js
18+
const logText = () => {
19+
console.log('A');
20+
setTimeout(() => {
21+
console.log('B');
22+
}, 0);
23+
console.log('C');
24+
}
25+
26+
logText()
27+
```
28+
29+
The output
30+
A
31+
C
32+
B
33+
34+
**Explanation** - Even though, I am passing 0 to the setTimeout() for the waiting period, because setTimeout() invokes a callback function - this callback function will be passed to an Event Loop. And we we know that - The event loop as a process is a set of phases with specific tasks that are processed in a round-robin manner - so the callback function will go through those phases and ultimately get executed. But during this process Node being Node, will be non-blocking, and so would NOT block the next lines of code which is the third line < console.log('C') >
35+
36+
#### Further Reading
37+
38+
https://medium.com/@siddharthac6/javascript-execution-of-synchronous-and-asynchronous-codes-40f3a199e687
39+
Worker pool is an execution model that spawns and handles separate threads, which then synchronously perform the task and return the result to the event loop. The event loop then executes the provided callback with said result.

Promise-Async-Await-Sequential-Execution/sequential-execution-of-codes-React-Node-Context-Master-Notes/sequential-execution-fundamental_working.md

-11
This file was deleted.

0 commit comments

Comments
 (0)