Read: Class 03 Async - 401-advanced-javascript-muna/amman-javascript-401d1 GitHub Wiki

Async

Javascript Runtime

V8 is the name of the runtime used in the Chrome web browser and in Node.js

Hoisting

where variables and function declarations are on the top of their scope before code execution.

The Call Stack

  • In Javascript, every synchronous function that is called is pushed onto a stack in V8.
  • The function on top of the stack is always the function that is currently executing.
  • When the function that is running returns it is “popped” off a stack.
  • This stack is referred to as a Call Stack.
  • V8 has a single Call Stack, therefor only one function can be running at a time.
  • The Call Stack is always printed to the screen when an error is thrown, which helps developers to trace where errors have occurred in their code.

The Callback Queue

  • When an asynchronous function called “foo” is invoked, it is pushed onto the V8 call stack.
  • Then “foo” makes a call to a browser/Node.js API and passes on a callback.
  • Then the “foo” function returns and is popped off of the call stack, and V8 keeps on executing synchronous code.
  • Meanwhile, the external browser/Node.js API is still running.
  • Once the external API has completed it’s task, it will pass any results into the callback and enqueue the callback on V8’s callback queue.
  • Functions stored on the callback queue are not executing, they are only waiting to be put onto the call stack.

The Event Loop

if the call stack is empty will dequeue callbacks from the V8 callback queue and pushing them on to the call stack.