I'm trying to fetch data from an API that only returns 100 items at a time and a marker to the next page. The API also has a field that contains the total number of items.
I am having trouble grasping even where to start designing this.
I know the remaining devices isn't updating after each call to get item marker.. what can I do?
if(remainingItems>0){
getItemMarker(tkn, jsonData["PagedItemList"]["NextMarker"]["_text"]).then( result => {
console.log(result);
jsonData = convertXMLtoJSON(result);
htmlResponse = htmlResponse + "<br><b>Part 2</b>"
htmlResponse = htmlResponse + htmlGetter(jsonData); //need to convert result before sending
return htmlResponse;
//I want to get part 3, 4..etc until I have no items left
}); //how do I ".then" over and over until I have no more items?
}
else{
return htmlResponse;
}
//I tried this
// but results in infinite loop
for(var i = 0; remainingItems>0; i++){
getItemMarker(tkn, jsonData["PagedItemList"]["NextMarker"]["_text"]).then( result => {
console.log(result);
jsonData = convertXMLtoJSON(result);
htmlResponse = htmlResponse + "<br><b>Part " + i + "</b>";
htmlResponse = htmlResponse + htmlGetter(jsonData); //need to convert result before sending
remainingItems = remainingItems - jsonData["PagedDeviceList"]["Items"]["Item"].length;
console.log(remainingDevices);
});
}
return htmlResponse;
First of all. It contains only 100 items for a reason. You should probably split the result into "pages", like in a typical webshop.
Anyways, imagine if there is a million items on a slow internet. You don't want to download all of that, and then show the result. Instead
In other words: update the HTML as soon as each "segment" is downloaded.
It's hard to show anything specific so see this as abstract code:
var part = 0;
function updateHTML(htmlResponse) { // 2
// code to update HTML, with either .innerHTML or .appendChild();
}
function downloadItems() { // 1
fetch(a_promise)
.then((result) => {
let jsonData = convertXMLtoJSON(result);
let htmlResponse = `<br><b>Part ${++i}</b>`;
let convertedToHTML = htmlGetter(jsonData)
updateHTML(htmlResponse + convertedToHTML) // 2
if (jsonData.length == 100) { // 3
downloadItems(); // 4
}
});
}