Skip to content

Instantly share code, notes, and snippets.

@atinux
Last active August 30, 2024 13:03
Show Gist options
  • Save atinux/fd2bcce63e44a7d3addddc166ce93fb2 to your computer and use it in GitHub Desktop.
Save atinux/fd2bcce63e44a7d3addddc166ce93fb2 to your computer and use it in GitHub Desktop.
JavaScript: async/await with forEach()
const waitFor = (ms) => new Promise(r => setTimeout(r, ms))
const asyncForEach = async (array, callback) => {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
const start = async () => {
await asyncForEach([1, 2, 3], async (num) => {
await waitFor(50)
console.log(num)
})
console.log('Done')
}
start()
@Korayem
Copy link

Korayem commented May 20, 2023

Why not use for await()?

const waitFor = (ms) => new Promise(r => setTimeout(r, ms))
const start = async () => {
  for await (num of [1, 2, 3]) {
    await waitFor(50)
    console.log(num)
  };
  console.log('Done')
}
start()

More info here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment