I'm trying to put a delay between each iteration in a loop using async await. I've got a helper sleep function:
const sleep = ms => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
And this is correctly waiting between each loop:
for (let i = 0; i < 5; i++) {
console.log('waiting')
await sleep(1000)
}
However, this is not waiting between each loop:
[0, 1, 2, 3, 4].forEach(async () => {
console.log('waiting')
await sleep(1000)
});
How can I modify the forEach code block to behave as the regular for loop block with delays between each iteration of the for loop?
async/await), you probably don't want to use.forEach. It was from before the language had proper iterators, which you can now use withfor (let/const value of array)(instead of a for-in loop as you have, which are also more-or-less obsolete).forEachitself would have toawaitthe promise returned by the callback. But.forEachcompletely ignores the return value.