Skip to content

Instantly share code, notes, and snippets.

@itsDiwaker
Last active April 16, 2020 12:35
Show Gist options
  • Save itsDiwaker/afb32c55d9203d5e6359aa95ecf5e4a7 to your computer and use it in GitHub Desktop.
Save itsDiwaker/afb32c55d9203d5e6359aa95ecf5e4a7 to your computer and use it in GitHub Desktop.
async for loop helper example
const asyncForEach = async (array, cb) => {
for (let index = 0; index < array.length; index++) {
await cb(array[index], index, array);
}
};
const wait = async (cb, timeout) => {
return new Promise((resolve) => {
setTimeout(() => {
cb();
resolve();
}, timeout);
});
}
(async () => {
console.log('START');
await wait(() => {
console.log('Before loop');
}, 1000);
await asyncForEach([1,2,3,4], async (item, idx, array) => {
await wait(() => {
console.log(item);
}, 2000);
});
await wait(() => {
console.log('After loop');
}, 1000);
console.log('END');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment