Skip to content

Instantly share code, notes, and snippets.

@anna-llorens
Forked from Atinux/async-foreach.js
Last active June 8, 2022 02:35
Show Gist options
  • Save anna-llorens/384e0aefbb4fd08458dcb95a2f31578e to your computer and use it in GitHub Desktop.
Save anna-llorens/384e0aefbb4fd08458dcb95a2f31578e to your computer and use it in GitHub Desktop.
JavaScript: async/await with forEach()
// Promise timeout
const waitFor = (ms) => new Promise(r => setTimeout(r, ms))
// forEach() async loop
const asyncForEach = async (array, callback) => {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
(async () => {
await asyncForEach([1, 2, 3], async (num) => {
await waitFor(50)
console.log(num)
})
console.log('Done')
}
@anna-llorens
Copy link
Author

Async Iteration over an array with 50ms of delay

@dexterarmy
Copy link

this a good implementation of asynchronous operation with async await. DId you leave calling the IIFE in the end intentionally ?

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