I am single-threaded non-block asynchronous concurrent language. I have a call stack, an event loop, a callback queue and some other APIs.
- On of the frusturating parts of synchronous programming is in an era of computers with multiple cores available. There is no sense waiting for something to be completed when my work is being done. It is up to the programming environment you are using (web browsers, in the case of web development) to provide you with APIs that allow you to run such tasks asynchronously.
- An example program for waiting for processes in UI is shown in below example link:
- The first button for clicking Fill button and then on clicking button for alert.
- It won’t function, as the operation to fill canvas is still running, and only on completion the alert button is shown.
- The issue with threads comes when one task you run depends on another, so multiple threads needn’t help always to improve speed.
Main thread: Task A Task B Promise: |async operation|
Coming on that topic of Event Loop, there is an excellent talk by Phillip Roberts about “What the heck is event loop anyways?”. It’s the most watched video for a particular reason.
Rough Notes from that talk
- blowing stack(MAximum call stack exceeded)
- What if browser were synchronous. In browser, we can’t do anything during program running, so browsers should be ideally asynchronous
- Simplest solution is asynchronous callbacks. In call stack how is behavious happening? After 5 seconds on Set time out function is printed again.
- In Stack, webAPIs, task Queue.
- The event loop elements in queue is only pushed when the stack is clear.
- Time out is minimum guaranteed time which is promised by Event loop
- Old style callbacks
- Newer promise style codes
In case of promises and callbacks they are different in many ways:
a) Promises helps in ordered execution of statements with then statements b) better error handling in case of promises c) In case of failure in callbacks it causes the call back hell, which can be pretty difficult to fix the issue d) Callbacks loose full control of how functions are executed when passing to a third party library.
Now as MDN concludes:
Also before concluding the link of this week:
- Did you know that switch/case statements are not available in Python?
- How to implement Sorting in Python, an excellent tutorial by Andrew Dalke and Raymond Hettinger
- Did you hear about the latest library Icream to never use print and log again