1

I'm very new to javascript and I'm working with the jeopardy api to to get jeopardy questions right now this is what i have

var request = new XMLHttpRequest();

request.open('GET', 'http://jservice.io/api/categories?count=6', true)
var arr = []
var clues = []
request.onload = function() {
    var data = JSON.parse(this.response)
    data.forEach(cat => {
        console.log(cat)
        arr.push(cat.id)
    })
    for (var i = 0; i < 6; i++) {
        var base = "http://jservice.io/api/category?id="
        var clueRequest = base.concat(arr[i])
        console.log(clues.push(clueRequest)) 
    }  
    
}

request.send()

The thing is that I want to now go into my clues list and do requests for those jsons because they hold the questions. How do I do this?

  • Your "clues list"? Where is this list? Also, consider using the Fetch API instead. There's little reason to deal with XHR these days. – Brad May 02 '20 at 21:28
  • Does this answer your question? [How to work with 2 XMLHttpRequest one dependent on another?](https://stackoverflow.com/questions/29051807/how-to-work-with-2-xmlhttprequest-one-dependent-on-another) – Tad Wohlrapp May 02 '20 at 21:29

2 Answers2

1

Here's an example of how to perform multiple data calls at once.

In this case, I'm using the fetch API with async/await features.

I get the data from the jeopardy api and then map over the data to set up an array of fetch promises. Then I use await Promise.all() to wait for the data to make it back. And at that point, we have an array of the clues objects.

async function getData() {

  const data = await (await fetch('https://jservice.io/api/categories?count=6')).json()
  
  const cluePromises = data.map(clue => fetch(`https://jservice.io/api/category?id=${clue.id}`).then(request => request.json()));
  const clues = await Promise.all(cluePromises);
  
  console.log(data);
  console.log(clues);
}
getData();
Zachary Haber
  • 10,376
  • 1
  • 17
  • 31
1

Not providing any code with solution but some general guidelines.

Create a function that will make the http request and return you the response. The function will take request method (e.g., GET, POST, PUT, DELETE), the url, request headers, and any POST parameters for example. Then the respose can be returned using a promise or via a callback function. You may have a look at promise and async/await. Then every time you need to make a request, you may call the function (even in the for loop where you are looking for clues)

You may also look at the alternatives (e.g., JQuery) to XMLHttpRequest.

Tuhin Paul
  • 558
  • 4
  • 11