Created
March 29, 2017 13:14
-
-
Save Eli-Goldberg/c516edb4b8f9c3329c91bb4411385ada to your computer and use it in GitHub Desktop.
Using async-await to iterate Promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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