Tag Archive for: async

Asynchronous iteration

Not all loop work the same in JavaScript. If you want an asynchronous loop you cannot use forEach because it will execute each iteration independently, however if you use a for of it will work as expected: it will await until the previous iteration has finished.

async () => {
  for (const e of elements)
    await getCloudData(e)

Be aware that in the previous code you will have to wait for each promise to resolve sequentially, which may not be as efficient if all your calls are unrelated. In that scenario, I would recommend you to use Promise.all() that would create parallel connections and will be just as late as the latest response.

async () => {
  let promises = []
  for (const e of elements)
  await Promise.all(promises)

Keep in mind that every browser has a specific limit to open parallel connections.

Asynchronous fetch with first class functions and closures

Get and post with/without authorization needed

Asynchronous fetch

Using fetch with asyncronous functions.

This way is even cleaner than using fetch by its own, check this out!