Skip to content

Instantly share code, notes, and snippets.

@AkashBabu
Last active May 16, 2018 10:15
Show Gist options
  • Save AkashBabu/b7affa4b786cd0c39350aeba7a79a662 to your computer and use it in GitHub Desktop.
Save AkashBabu/b7affa4b786cd0c39350aeba7a79a662 to your computer and use it in GitHub Desktop.
Executing Async loop in sequence using Generator Functions in NodeJS
function* generatorFn(arr = [], asyncFn) {
for(let item of arr) {
// Alter this function according to your needs.
// Also note that the below code would remain the same even in case of async-await functions
yield asyncFn(item)
}
}
async function execSequentially(arr, asyncFn) {
let gen = generatorFn(arr, asyncFn)
let result = gen.next();
while(!result.done) {
let val = await result.value
console.log(val)
result = gen.next()
}
}
function asyncFn(item){
// Random timeout is used just to confirm the true sequentialization of Async loop
return new Promise(resolve => setTimeout(resolve, 1000 + 100, item))
}
// This would go through the entire array creating a timeout for each item,
// but would execute the timeout one-after-the-other (sequentially)
execSequentially([123,2,3,4], asyncFn)
@AkashBabu
Copy link
Author

This solves the case where the code looks like below:
[1,2,3,4].forEach(async i => { await new Promise(resolve => setTimeout(resolve, Math.random() * 1000 + 100, item)) })

If you execute the above code you may find different item being printed in unordered sequence.
But instead if you use the above gist, then order would be sequential

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment