Created
October 14, 2014 16:26
-
-
Save tyler-johnson/c4d5971512d7b2c62f04 to your computer and use it in GitHub Desktop.
Asynchronous while loop for ES6 Promises.
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
function asyncWhile(condition, action, ctx) { | |
var whilst = function(data) { | |
return condition.call(ctx, data) ? | |
Promise.resolve(action.call(ctx, data)).then(whilst) : | |
data; | |
} | |
return whilst(); | |
} |
Thank you for this useful piece of code!
IARI, it doesn't cause a stack overflow because the recursion is asynchronous: .then(whilst)
is called from the event loop, not from inside whilst()
itself.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Won't that cause stack overflows?