Essential CSS
JavaScript Roadmap
Learn JavaScript
Mastering Web Typography
Practical Astro
Understanding Async JS
Unorthodox Tailwind
API Masterclass
Build and Deploy
The Beginner Freelancer
Real World Node
Profile Billing Logout
Understanding Async JS
Lesson Plan
  1. Introduction
    1. What is Asynchronous JS?
    2. Callbacks are not automatically asynchronous
    3. What is an API?
    4. Evolution of HTTP APIs
    5. Ajax vs Asynchronous JavaScript
  2. Fundamental Concepts
    1. How to fetch resources
    2. Using XHR
    3. Using the Fetch API
    4. Using libraries
    5. Core JavaScript concepts
    6. Understanding Promises
    7. Understanding Async Functions
    8. Understanding the Event Loop
    9. Understanding JSON
    10. Async JS Best Practices
    11. Using Optimistic UI
  3. Understanding Rest API
    1. Diving into Rest APIs
    2. The Rest Architecture
    3. The Rest Structure
    4. Anatomy of a Request
    5. What's an endpoint
    6. Request methods
    7. Understanding request headers
    8. Understanding the request body
    9. Authentication
    10. Basic Authentication
    11. Bearer Authentication
    12. Authenticating with API keys and API Secrets
    13. Cross Origin Resource Sharing
    14. Anatomy of a response
    15. HTTP Statuses
    16. Response headers
    17. The response body
    18. Handling Errors
    19. Reading API documentations
    20. Understanding Curl
  4. Node Basics
    1. Why we are using Node
    2. Command Line Basics
    3. Installing Node
    4. Managing dependencies
    5. Using ES Modules in Node
    6. Using Node
    7. Restarting the server automatically
    8. Sending requests via Node
    9. Protecting API keys and secrets
  5. Building a server
    1. What's a server
    2. Building a simple server with Express
    3. Two kinds of servers
    4. API Server architecture
    5. Handling routes
    6. Understanding Middlewares
    7. Enabling CORS
    8. Receiving data
    9. Sending responses
    10. Handling errors in Express
    11. Using the server as a proxy
    12. Minimum viable server
  6. Open Authorization
    1. Open Authorisation (OAuth)
    2. Authenticating with Access Tokens
    3. Obtaining Access Tokens
    4. Public and Confidential Clients
    5. Authorisation Code Grant
    6. Understanding scope
    7. Proof Key for Code Exchange (PKCE)
    8. PKCE with Twitter
    9. Dynamic state and `code_verifier`
    10. Saving the access token in cookies
    11. Passing access tokens to the browser
    12. Saving the access token in local storage
    13. Refresh Token Grant
    14. Device Code Grant
    15. Client libraries vs REST
  7. Building Social Media Logins
    1. Introduction
    2. Starter Files
    3. Creating SSL certificates
    4. Login in with Github
    5. Github: Saving the token to local storage
    6. Github: Persisting the login status
    7. Login with Twitter
    8. Twitter: Saving the token to local storage
    9. Twitter: Persisting the login status
    10. Twitter: Refreshing the access token
    11. Login with Facebook
    12. Facebook: Saving the token to localStorage
    13. Facebook: Persisting the login status
    14. Facebook: Refreshing the access token
    15. Login with google
    16. Google: Saving the token to localStorage
    17. Google: Refreshing the access token

Understanding the Event Loop

5m:51s

The backbone of all asynchronous JavaScript operations is the event loop. So you need to know the event loop to understand how asynchronous JavaScript works.

Here, I recommend you watch a JSConf talk by Philips Roberts and another by Jake Archibald.

  • Philips Roberts talks about a basic event loop and how it works
  • Jake Archibald goes deeper into Tasks and Microtasks and how they interact with the Event Loop.

In this lesson, I’m going to combine what I learned from both talks into a coherent explanation that helps you understand how the entire event loop works.

The Event Loop

There are four layers in the Event Loop:

  • The Call Stack
  • Web and Node APIs
  • The Task Queue (or Macrotask Queue)
  • The Microtask Queue

The Call Stack

The Call Stack is where we run JavaScript code. Each part that needs to be evaluated goes into the call stack when it’s read by JavaScript. When the evaluation is complete, it is removed from the Call stack.

Simple Example

console.log('one')
console.log('two')

Here’s what happens in this simple example:

  1. console.log('one') will be added to the call stack.
  2. JavaScript will run console.log('one') immediately.
  3. console.log('one') is removed from the call stack since it is complete now.
  4. Repeat the three steps above for console.log('two')
Note

The console.log statement shows up at the bottom of this image because the Call Stack works in a LIFO (Last-in, First-out) way.

Complex Example

In a complex example, we have a function called runProgram that will run another function, sayHello.

function runProgram() {
console.log('start')
sayHello()
console.log('end')
}
function sayHello() {
console.log('hello')
}
runProgram()

I’m going to explain what happens through videos for this lesson, so please have your sound turned on!

Web and Node APIs

Functions that provide you with asynchronous behaviour are usually not built into JavaScript directly. They’re built into browsers or Node instead.

Depending on where you use them, you call them Web or Node API respectively.

  • In browsers: Web API
  • In Node: Node API
Note

In case you were wondering, Node is backend JavaScript. We’ll talk about Node later as it’s necessary for most Rest API requests.

setTimeout is an example of such a function. Let’s see how setTimeout interacts with the call stack.

setTimeout(callback, 3000)

Here’s what will happen:

  1. setTimeout appears in the call stack
  2. setTimeout is removed from the call stack since it’s done
  3. 3 seconds later, the callback appears in the call stack.

How does callback magically appear in the call stack after 3 seconds?

Well, functions like addEventListener and setTimeout rely on the browser’s environment to keep of track events and timers.

We don’t know how they work because we can’t access the browser’s internals. (Ditto for Node if you’re in a Node environment).

One possible theory is the browser spins up multiple threads — one for each asynchronous action — to keep track of the events going on. I’m not sure whether this is the truth because I haven’t found evidence to prove or disprove this hypothesis.

The best thing we can do is treat the Web (or Node) APIs like black boxes that magically know when it is appropriate to call the callback.

When the time is appropriate these black boxes add the callback back into the call stack as a Task or a Microtask. Whether the callback gets added to the Task Queue or the Microtask Queue depends on the API used.

For example:

  • setTimeout adds the callback into a Task Queue
  • A promise adds the callback into a Microtask Queue
  • Mutation Observer adds the callback into a Microtask Queue

The best to check if the API uses a Task or Microtask is to check the specifications.

Note
A Microtask may also be called a Job in the spec.

Task Queue and Microtask Queue

JavaScript has a Task queue and a Microtask Queue.

These queues are similar to an actual queue in real life. They use a FIFO (First-in, First-out) structure, which means the callback that comes into the queue first will be handled first.

  • When an API detects it should fire a callback, the callback gets added to the respective queues.
  • When the call stack is empty, JavaScript will check the queues and invoke the callback.

Let’s keep things simple by talking about the Task queue first.

setTimeout(callback, 3000)

Clearing the Call Stack comes first.

JavaScript prioritizes clearing the call stack before getting any tasks from the queues. To prove this, we can run an expensive operation that takes longer than the amount of time we set in setTimeout.

// 1 Second Timeout
setTimeout(_ => {
console.log('Callback')
}, 1000)
// This takes about 3 seconds on my computer
for (let index = 0; index < 30000; index++) {
console.log(index)
}

Notice the callback log statement doesn’t appear in the middle of the loop.

This shows that JavaScript prioritizes clearing the call stack first as the loop is still in the call stack at that point. It doesn’t let any task in the queue disrupt the work it’s doing. You can think of it like a focused worker who refuses to get distracted.

Microtasks Queue — the priority queue

Disneyland has two queues for every ride — a priority queue and a normal queue. The same concept applies to the call stack as well.

  • The priority queue is the Microtask queue
  • The normal queue is the Task queue

JavaScript will clear all tasks in the Microtask queue before it clears any task in the Task Queue. We can prove this by creating a promise and setTimeout within the same code.

// Resolves immediately
setTimeout(_ => {
console.log('Timeout')
}, 0)
// Promise also resolves immediately
Promise.resolve().then(_ => {
console.log('Promise')
})
// This proves the call stack must completed and cleared before Microtasks and Tasks can be called.
console.log('Last')

This explanation matches the console.log statements we see in the console.

Console.log statements from the code above

In the event that a Microtask triggers another Microtask, the new Microtask must be completed before JavaScript looks at the Task queue. We can see this in action with the following code:

// Resolves immediately
setTimeout(_ => {
console.log('Timeout')
}, 0)
Promise.resolve()
// First Microtask
.then(_ => {
console.log('Promise')
})
// Second Microtask
.then(_ => {
console.log('Promise 2')
})
console.log('Last')

The console.log statements agree with the above explanation as well.

Console of the above code

A 0ms callback doesn’t trigger immediately

You can deduce from the above example a callback of 0ms doesn’t mean the callback will be triggered immediately. The callback still needs to wait for its turn.

Further Reading