Skip to content

Instantly share code, notes, and snippets.

@Eli-Goldberg
Created March 29, 2017 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Eli-Goldberg/c516edb4b8f9c3329c91bb4411385ada to your computer and use it in GitHub Desktop.
Save Eli-Goldberg/c516edb4b8f9c3329c91bb4411385ada to your computer and use it in GitHub Desktop.
Using async-await to iterate Promises
async function waitAndPrint(toPrint) {
await new Promise((resolve, reject) => {
setTimeout(() => {
console.log(toPrint);
resolve();
}, Math.random() * 1000);
});
}
const arrayOfNumbers = [1, 2, 3, 4];
async function forEachAsync(array, func) {
for (const item of array) {
await func(item);
}
}
forEachAsync(arrayOfNumbers, async (num) => {
await waitAndPrint(num)
});
console.log('hello !');
// hello !
// 1
// 2
// 3
// 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment