Skip to content

Instantly share code, notes, and snippets.

@edgarberm
Created December 22, 2016 17:26
Show Gist options
  • Save edgarberm/3c5abb63c178a21c8e9c72d61fda5c83 to your computer and use it in GitHub Desktop.
Save edgarberm/3c5abb63c178a21c8e9c72d61fda5c83 to your computer and use it in GitHub Desktop.
Asynchronous iterations
/**
* Asynchronous Loop
* @param {Int}
* @param {Function}
* @param {Function}
* @return {Object}
*
*
* Usage:
*
* asyncLoop(iterable.length, loop => {
* someAsyncFunction().then(data => {
* console.log(loop.index())
* loop.next()
* }).catch(error => throw error)
* },
* () => {
* console.log('Asynchronous Loop is done!')
* })
*/
const asyncLoop = (iterations, func, callback) => {
let i = 0
let done = false
let loop = {
// Next loop iteration
next () {
if (done) return
if (i < iterations) {
i ++
func(loop)
} else {
done = true
callback()
}
},
// Get loop index
index () {
return i - 1
},
// Break loop
break () {
done = true
callback()
}
}
// Start
loop.next()
return loop
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment