Skip to content

Instantly share code, notes, and snippets.

@iheartmedia-matt
Forked from Atinux/async-foreach.js
Last active February 13, 2020 22:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iheartmedia-matt/e3be26db967eba06b4f783b924b37596 to your computer and use it in GitHub Desktop.
Save iheartmedia-matt/e3be26db967eba06b4f783b924b37596 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 = (array, callback) => {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}*/
// ES6 Compliant `asyncForEach`
// Resolves await reserved keyword
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment