0

I'm currently looping through a paginated API like this, but it seems extremely bulky and repeated and I'm wondering if there's a simpler and faster way to do this.

async function myFunc () {
  const totalPages = await getTotalPages()

  const res = await new Promise(async (resolve) => {
    const completedPages = []
    const failedPages = []
    let allPages = []
    for (let pageNum = 0; pageNum < totalPages; pageNum++) {
      getPage(pageNum).then((page) => {
        allPages.push(...page)

        completedPages.push(pageNum)
        if ((completedPages.length + failedPages.length) === totalPages) {
          return resolve({ all_pages: allPages })
        }
      }).catch((err) => {
        console.log(pageNum, err)
        failedPages.push(pageNum)
        if ((completedPages.length + failedPages.length) === totalPages) {
          return resolve({ all_pages: allPages })
        }
      })
    }
  })
  return res
}
Cloud
  • 1
  • 1
    [Never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! It looks like you are trying to reinvent `Promise.allSettled`. – Bergi Sep 01 '21 at 23:28
  • Further to point 1 - why is it async anyway! You never `await` there – Bravo Sep 01 '21 at 23:32
  • There's nothing "faster" - as this will take as long as it takes anyway - simpler, yes, replace everything after the second line with `return Promise.allSettled(Array.from({length:totalPages}, (_, pageNum) => getPage(pageNum))).then(results => results.filter(({reason}) => !reason).map(({value}) => value));` – Bravo Sep 01 '21 at 23:42

0 Answers0