My task involves retrieving 100 objects through an ajax request by passing an ID. However, I can only send a maximum of 20 IDs at a time. As a solution, I am sending them in batches of 20 until all the data is received from the server. What would be the most efficient way to accomplish this asynchronously?
To test this process, I have set up a global array. After receiving data from each request, I merge it with the existing array:
window['p'] = [];
function getAllProducts(products) {
var counter = 0;
while(counter < products.length){
(function(counter){
var request = new XMLHttpRequest();
var url = '/api/catalog_system/pub/products/search?';
// Concatenate all the IDs with the URL
if (counter === 0){
url += 'fq=skuId:'+products[0].sku
for (var i = 1; i < 20; i++) {
url+= '&fq=skuId:'+products[i].sku;
}
} else {
for (var i = counter; i < counter + 20; i++) {
if (typeof products[i] === 'undefined') {
break;
}
url+= '&fq=skuId:'+products[i].sku;
}
}
request.open('get',url,true);
request.onreadystatechange = function(){
if (request.status == 200 || request.status == 206 && request.readyState == '4') {
var data = JSON.parse(request.responseText);
console.log(data);
window['p'].push(data);
}
}
request.send(null);
console.log(request);
}(counter))
counter+=20;
}
}
getAllProducts(productArray);