Requesting many resources with XHR

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Requesting many resources with XHR

Requesting many resources with XHR

We need events to fetch resources with XHR. If we want three resources, we can use three event listeners.

const burgerRequest = new XMLHttpRequest()
const friesRequest = new XMLHttpRequest()
const drinkRequest = new XMLHttpRequest()

burgerRequest.addEventListener('load', e => { /* Burger's ready! */ })
burgerRequest.open('GET', 'Burger Link')
burgerRequest.send()

friesRequest.addEventListener('load', e => { /* Fries' ready! */ })
friesRequest.open('GET', 'Fries Link')
friesRequest.send()

drinkRequest.addEventListener('load', e => { /* Drink's ready! */ })
drinkRequest.open('GET', 'Drink Link')
drinkRequest.send()

There’s a problem with the above approach—we don’t know when all our resources return from the server. We only know about one resource in each event listener.

One way to get all three resources is to wait for a response before sending the next request out. That means:

  1. Send request for burger
  2. Wait for burger to be ready
  3. Send request for fries
  4. Wait for fries to be ready
  5. Send request for drink
  6. Wait for drink to be ready

Here’s what it might look like:

burgerRequest.addEventListener('load', e => {
  // Burger is ready! Send request for fries now!
  const burger = e.target

  const friesRequest = new XMLHttpRequest()
  friesRequest.addEventListener('load', e => {
    // Fries is ready! Send request for drink now!
    const fries = e.target

    const drinkRequest = new XMLHttpRequest()
    drinkRequest.addEventListener('load', e => {
      const drink = e.target
      serveMeal(burger, fries, drink)
    })
    drinkRequest.open('GET', 'Drink Link')
    drinkRequest.send()
  })
  friesRequest.open('GET', 'Fries Link')
  friesRequest.send()
})

There are two problems.

First, we sent one request when another request completes. This means we’re wasting time if burger, fries and drinks can be requested independently.

Second, the code is confusing and complicated. We have callbacks in callbacks. This nested callback pattern is often called callback hell. We want to avoid callback hell.

The ideal solution to fetching many requests at once lies with promises. You can find the promise-based solution in this lesson.

Note: Axios lets you use promises even if you use XHR.