0

I have code that is making an HTTP request in a forEach iteration. The problem is, all of the HTTP requests are firing off at once.

const main = async () => {
    
    items.forEach(async (i: Item) => {
        const response = await fetch(/* code and stuff */)
    });
}

main()

I am flooding the server with requests in this particular case as all items are subsequently firing off.

Is there a way to make the fetch synchronous in this case, so that only one is being sent to the URL behind fetch() at a time?

randombits
  • 47,058
  • 76
  • 251
  • 433
  • 1
    Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Idrizi.A Oct 14 '22 at 22:11
  • 1
    Might be asking the wrong question. Request throttling and load balancing are usually handled by the web server. Using sync or async/await on the client for throttling will not scale because the clients are all operating async of each other. – Yogi Oct 15 '22 at 00:05

1 Answers1

0

You should iterate over the items in a for loop and await each fetch before processing the following one.

const main = async () => {
    
    for (let item of items) {
      await fetch("url with item")
    }
}

main()

If you want a to chunk "a few" items at once, check this article I wrote a while back

Abdellah Hariti
  • 657
  • 4
  • 8