0

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.

Quirk
  • 165
  • 1
  • 2
  • 12
  • 2
    Your `loop` function currently does not return a promise, breaking promise chain. Then `forEach` does not return as well, you most likely need `map`. And finally, there is no point in manually creating a `new Promise` (it is considered to be an antipattern) `fetch` already returns a promise. – Yury Tarabanko Feb 27 '23 at 11:26
  • There is pretty much no need to use `thenables` these days, pretty much all major browsers have `async / await`, and if you do need to target older browsers you really should be transpiling & pollyfilling to get modern features. With `async/await` your code could just use a standard `for of` and be way easier to follow. – Keith Feb 27 '23 at 11:30

0 Answers0