Last active
April 16, 2020 12:35
-
-
Save itsDiwaker/afb32c55d9203d5e6359aa95ecf5e4a7 to your computer and use it in GitHub Desktop.
async for loop helper example
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
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