Currently, I am making modifications to an application that processes REST API calls in batches, such as executing 500 total calls in groups of 10. I require help in downgrading my JavaScript function, which currently utilizes ES6+ features, to an ES5 equivalent (without arrow functions or async/await).
In the initial version of my application, which was utilized in environments supporting ES6+ functions like arrow functions and async/await, the working function looked like this:
Original Function:
// Async function to process rest calls in batches
const searchIssues = async (restCalls, batchSize, loadingText) => {
const restCallsLength = restCalls.length;
var issues = [];
for (let i = 0; i < restCallsLength; i += batchSize) {
//create batch of requests
var requests = restCalls.slice(i, i + batchSize).map(restCall => {
return fetch(restCall)
.then(function(fieldResponse) {
return fieldResponse.json()
})
.then(d => {
response = d.issues;
//for each issue in response, push to issues array
response.forEach(issue => {
issue.fields.key = issue.key
issues.push(issue.fields)
});
})
})
await Promise.all(requests)
.catch(e => console.log(`Error in processing batch ${i} - ${e}`))
d3.selectAll(".loading-text")
.text(loadingText + ": " + parseInt((i / restCallsLength) * 100) + "%")
}
d3.selectAll(".loading-text")
.text(loadingText + ": 100%")
return issues
}
The current code correctly divides the rest calls into batches of 10 initially, but I am facing challenges resolving the Promise so the for-loop can progress.
My Revised Work-in-progress Function:
//Async function process rest calls in batches
function searchIssues(restCalls, batchSize, loadingText) {
const restCallsLength = restCalls.length;
var issues = [];
for (var i = 0; i < restCallsLength; i += batchSize) {
//create batch of requests
var requests = restCalls.slice(i, i + batchSize).map(function(restCall) {
return fetch(restCall)
.then(function(fieldResponse) {
return fieldResponse.json()
})
.then(function(data) {
console.log(data)
response = data.issues;
//for each issue in response, push to issues array
response.forEach(function(issue) {
issue.fields.key = issue.key
issues.push(issue.fields)
});
})
})
return Promise.resolve().then(function() {
console.log(i)
return Promise.all(requests);
}).then(function() {
d3.selectAll(".loading-text")
.text(loadingText + ": " + parseInt((i / restCallsLength) * 100) + "%")
});
}
d3.selectAll(".loading-text")
.text(loadingText + ": 100%")
return issues
}
My main query is, how can I ensure proper resolution of the Promise once the group of 10 rest calls is completed, allowing the iteration through the for-loop to continue smoothly?
Just as a point of reference, I attempted compiling the original function using Babel, but it failed to compile in my Maven application, hence the decision to start afresh with rewriting.