0

I need to sequentially iterate through an array of URLs, awaiting asynchronous responses for each, before moving to the next URL.

I was initially expecting this to be synchronous. (I also tried .map in place of .forEach)

const urls = [ 'https://url.com', 'https://url.com/difPage', 'https://url.com/difPage2' ]

urls.forEach(async url => {
    const data = await performAsyncUrlFunction(url)
})
shanestreator
  • 69
  • 1
  • 1
  • 7
  • 1
    Just use a regular loop and still have `await` inside. No need for recursion or anything at all complex. – VLAZ Aug 23 '23 at 20:01
  • forEach loop I can understand, but why wont it work with map? – Nazrul Chowdhury Aug 23 '23 at 20:06
  • 1
    @NazrulChowdhury For the same reason it doesn't work with forEach - in both cases the iteration is done in full, without waiting for async execution of the callback. If you want to do a *sequential* map, then either use a regular loop or collect the result into an array with a regular loop and `await` then map over the collected array. If you don't care about doing it sequential, map into promises and use `Promise.all()` – VLAZ Aug 23 '23 at 20:08
  • Ah thanks! Thought I had tried a regular for loop and it wasn't working. Just tested and it worked. Amazin'. Will update answer. – shanestreator Aug 23 '23 at 20:39

1 Answers1

0

Simplest answer is a for loop. (Thank you @VLAZ)

For reference, the performAsyncUrlFunction was using Puppeteer to extract images from the provided url and saving them.

const urls = [ 'https://url.com', 'https://url.com/difPage', 'https://url.com/difPage2' ]

const asyncFunc = async () => {

    for (let i = 0; i < urls.length; i++) {
        await performAsyncUrlFunction(urls[i])
    }

}

asyncFunc()
shanestreator
  • 69
  • 1
  • 1
  • 7