taylorbell.com

Sometimes I find myself needing to do something asynchronously for each item in an array. For example, quering an API for every date in a range.

const dates = [
  '20200101',
  '20200102',
  '20200103',
  '20200104'
]

I write an async function, that I'll call at the bottom of the file:

async function driver() {
    
}

driver()

Use the for of loop inside of the function to await the result of an operation:

async function driver() {
  for (let d of dates) {
    await someStuffGetsDone(d)
    console.log(`Done with ${d}`)
  }  
}

All together now:

const dates = [
  '20200101',
  '20200102',
  '20200103',
  '20200104'
]

async function driver() {
  for (let d of dates) {
    console.log(d)
    const f = await createPredictionFile(d)
    console.log(`Done with ${d}`)
  }

  console.log("done with all")
}

driver()