Skip to content

Instantly share code, notes, and snippets.

@tyler-johnson
Created October 14, 2014 16:26
Show Gist options
  • Save tyler-johnson/c4d5971512d7b2c62f04 to your computer and use it in GitHub Desktop.
Save tyler-johnson/c4d5971512d7b2c62f04 to your computer and use it in GitHub Desktop.
Asynchronous while loop for ES6 Promises.
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();
}
@IARI
Copy link

IARI commented Jul 1, 2015

Won't that cause stack overflows?

@solendil
Copy link

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