A quick intro to Asynchronous JS

Do you know how code executes in JS?

Have you come up with the following things in JS?

1. Multithreading
2. Race Conditions
3. Parallel requests
4. Lock up browsers
5. Single threaded
6. Callbacks
7. Cooperative Concurrency
8. Event Loop
9. Non-blocking I/O


Asynchronous programming is one of those programming paradigms that’s extremely difficult to fully understand, until you’ve done enough of it in practice

Examples :


Concurrency Model in JS:

It is quite different than other languages like C# or Java.

JS engine can only execute one peiece of code at a time. So by default JS has single threaded nature. 

Event Loop:
The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the code after an async function has executed.

Blocking vs Non-blocking

Blocking refers to operations that block further execution until that operation finishes. Non-blocking refers to code that doesn't block execution. In the given example, localStorage is a blocking operation as it stalls execution to read. On the other hand, fetch is a non-blocking operation as it does not stall alert(3) from execution.
// Blocking: 1,... 2
alert(1);
var value = localStorage.getItem('foo');
alert(2);

// Non-blocking: 1, 3,... 2
alert(1);
fetch('example.com').then(() => alert(2));
alert(3);


Comments

Popular posts from this blog

Interesting Facts about MVC framework`

AngularJS - Experiencing new era

ReactJS