简体   繁体   中英

How do I deal do two API calls in javascript?

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?

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();

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 (eg, 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 (eg, JQuery) to XMLHttpRequest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM