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

Async JS Best Practices

3m:6s

There are two mandates when it comes to Asynchronous JavaScript

  1. Reduce unnecessary requests
  2. Reduce wait time as much as possible

Reducing unnecessary requests is easy — just don’t fetch information that the user doesn’t require.

We’re going to focus on the second mandate as it’s a bit more complex.

Reducing wait times

You can reduce wait times using two methods:

  1. Batching requests when you can
  2. Use Optimistic UI

Batching requests when you can

When you send a request, you need to wait for a response from the server.

How fast the response comes back depends on many factors such as:

  1. Your internet speed
  2. The latency
  3. How far the server is away from you
  4. Whether the server uses a CDN
  5. How large is the data

Most of the time, you’ll get a noticeable lag time between a request and a response. So you should always batch requests together when you can.

Note

This lag time might not exist when you’re fetching from localhost since you’re fetching from your own computer.

How to batch requests

You can batch requests with a method called Promise.all.

Promise.all takes in an array of promises.

When all promises are fulfilled, you can get the respective values in then.

Promise.all([promise1, promise2])
.then(values => {
const [valueOne, valueTwo] = values
console.log(valueOne)
console.log(valueTwo)
})

Any error from any promise within Promise.all will send the code into a catch call. You can then handle the error like a normal promise.

Promise.all([promise1, promise2])
.catch(error => {
/*Handle error*/
})

What happens when you batch requests

We can create a fake request to demonstrate the difference between batching requests and not batching requests.

Here, we are going to do a few things:

  1. We’re going to create a request Promise that mocks a fetch function.
  2. This request will have a 1-second lag time.
  3. We’ll write two sets of code code — one that batch requests and one that doesn’t.
  4. Then we’ll compare the time it takes to get the response.

First, let’s create the request function with a 1-second lag time.

We can use setTimeout to make this function.

To make things simple, we will make the response value the same value that was passed into the request.

// Promises that let us create a delay
function delay(duration) {
return new Promise(resolve => {
setTimeout(resolve, duration)
})
}
// Returns a promise with a value after 1 second
function request(value) {
return delay(1000).then(() => {
return value
})
}

If you use this request function, you should now see a time lag of 1 second.

request('something').then(value => console.log(value))

Next, let’s write two sets of code:

  • We’ll use request to generate two requests.
  • In the non-batching code, we’ll use await to wait for the first request to finish before we send the second request.
  • In the batching code, we’ll use Promise.all to send both requests together.

Here’s the non-batching code with await.

const one = await request('one')
console.log(one)
const two = await request('two')
console.log(two)

For this code, you’ll notice it takes 2 seconds to for all the requests to be complete.

Now here’s the batching code with Promise.all.

Promise.all([request('one'), request('two')]).then(values => {
const [valueOne, valueTwo] = values
console.log(valueOne)
console.log(valueTwo)
})

For this code, you’ll notice it only takes 1 second to complete both requests.

Reduced fetch time from 2 seconds to 1 second

That’s all you have to know about batching requests.

We’ll talk about Optimistic UI in the next lesson.