Created
December 22, 2016 17:26
-
-
Save edgarberm/3c5abb63c178a21c8e9c72d61fda5c83 to your computer and use it in GitHub Desktop.
Asynchronous iterations
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
/** | |
* 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