Skip to content

Instantly share code, notes, and snippets.

@dalaidunc
Created August 25, 2017 15:22
Show Gist options
  • Save dalaidunc/9f0e300c76a551ec99590baa68c4392d to your computer and use it in GitHub Desktop.
Save dalaidunc/9f0e300c76a551ec99590baa68c4392d to your computer and use it in GitHub Desktop.
Improper async forEach loop
// define a Promise wrapper around the setTimeout function
function wait (fn, time) {
return new Promise(resolve => setTimeout(() => {fn();resolve();}, time));
}
const arr = ['a', 'b', 'c', 'd'];
// if we want to call an async function for each element in the array
// in series, this would not work:
arr.forEach(async (item, index) => {
await wait (() => console.log(item), 500);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment