I'm having issues iterating through an array of potentially recursive API calls.
I'm trying to build a loop()
function that recursively calls an API that paginates the results until that API returns response.isLast == true
, at which point we know we've collected all the results for that particular series of API calls.
The issue is that I don't know how many paginated responses I need to call until I see that isLast
value. I've tried integrating various combinations of Promises, Promise.all() functions and async/await combinations but for some reason I can't get the forEach function to resolve before moving on to the next block of code.
The code snippet is as follows:
array.forEach(function (element) {
element.resultsArray = []
const loop = (startAt) => {
new Promise(function (resolve) {
//make paginated api request
return fetch('/api/request?startAt=' + startAt)
.then(function (fieldResponse) {
//process API response
return JSON.parse(fieldResponse.body)
})
.then(function (results) {
//process results
results.forEach(function (result) {
element.resultsArray.push(result)
})
if (results.isLast) {
//done! move on to next element
resolve(element)
} else if (!results.isLast) {
//more pagination needed, need to create another promise and loop through results
return loop(startAt + 50)
}
})
.catch(function (d) {
console.log(d)
})
})
}
return loop(0)
})
// the next code block starts before all the fetch promises are resolved!?
// NEXT CODE BLOCK
Any help to ensure the forEach loop is completed before the next code block would be much appreciated.