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 :
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 :
- Weather http://plnkr.co/edit/ZOAaSdtnfvR6WwiuVZ6s
- Avoid Blocking – Red Background http://plnkr.co/edit/z29VyH5BPvC4oc40EyOu
- setTimeout Pyramid Challenge http://plnkr.co/edit/DGiHFQOQfnipCcpex2RH
- Drag and Drop Red Box http://plnkr.co/edit/SmSpPS5ZgPvkgn8RE6y1
- Timer onReady http://plnkr.co/edit/gafgKCrxnDIJ6YaG9Jpx
- Timer measure http://plnkr.co/edit/kPOgzEuIvUmN4o6Jenem
- Progress Number Crunching - Web Worker https://plnkr.co/edit/Yy7BOZU9sIa8EyrxJwGH
- Event Listeners Are Synchronous http://plnkr.co/edit/mDvSHpF3HcTjtvltGmQn
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
Post a Comment