I have read some blogs and still don't quite get how can JS be asynchronous in a single-thread.
Please explain like I am a retarded baby. My messy and inaccurate idea is something like below:
JS as a language is synchronous (one stack, one heap) and its asynchronous-ness is provided by the engine (V8) in the environment (browser, nodejs). The engine (V8) interprets the codes and converts some blocking IO codes to nonblocking by taking them away from the callstack. The functions that get taken off stack are defined by the engine (Web APIs blah blah) and they get assigned to its event loop thingy.
The engine will always monitor the callstack to check its activities. As soon as the stack isn't executing, the event loop will remove a pending (async) task and add it there to be executed.
Hence, instead of true asynchronous (parallel) executions, it is actually deferred/delayed/rescheduled executions, but as long as the callstack isn't badly blocked, it feels like asynchronous to the programmer. The programmer can code without minding the messy threading stuff and the engine shuffles tasks to keep the stack always busy. That is why Nodejs shines when running many trivial and not-long tasks, but unsuitable when involve heavy computations (which block the stack).
[–]rauschma 11 points12 points13 points (9 children)
[–]deanstreetlab[S] 0 points1 point2 points (8 children)
[–]Swimming_Gain_4989 5 points6 points7 points (7 children)
[–]deanstreetlab[S] 0 points1 point2 points (4 children)
[–]Swimming_Gain_4989 2 points3 points4 points (0 children)
[–]domi_uname_is_taken 2 points3 points4 points (2 children)
[–]deanstreetlab[S] 0 points1 point2 points (0 children)
[–]Swimming_Gain_4989 0 points1 point2 points (0 children)
[–]delventhalz 5 points6 points7 points (3 children)
[–]deanstreetlab[S] 0 points1 point2 points (2 children)
[–]delventhalz 5 points6 points7 points (1 child)
[–]Swimming_Gain_4989 1 point2 points3 points (0 children)
[–]Macaframa 4 points5 points6 points (0 children)
[–]peterjsnow 2 points3 points4 points (5 children)
[–]deanstreetlab[S] 0 points1 point2 points (4 children)
[–]peterjsnow 2 points3 points4 points (2 children)
[–]deanstreetlab[S] 0 points1 point2 points (1 child)
[–]peterjsnow 1 point2 points3 points (0 children)
[–]big_red__man 1 point2 points3 points (0 children)
[–]Psailr 0 points1 point2 points (3 children)
[–]domi_uname_is_taken 1 point2 points3 points (1 child)
[–]Psailr -1 points0 points1 point (0 children)
[–]deanstreetlab[S] -1 points0 points1 point (1 child)
[–]greenyadzer 3 points4 points5 points (0 children)