Skip to content

Instantly share code, notes, and snippets.

@PAEz
Forked from victorquinn/promise_while_loop.js
Last active February 5, 2017 06:33
Show Gist options
  • Save PAEz/ff6a00f8072907f2d6a7 to your computer and use it in GitHub Desktop.
Save PAEz/ff6a00f8072907f2d6a7 to your computer and use it in GitHub Desktop.
Promise "loop" using the Bluebird library Updated to p1nox's comment from the original
/*
p1nox commented 19 days ago
I was digging a bit about this and I found some interesting links:
petkaantonov/bluebird#553 (comment)
http://stackoverflow.com/a/29396005
http://stackoverflow.com/a/24660323
Simplifications:
*/
function promiseWhile(predicate, action) {
function loop() {
if (!predicate()) return;
return Promise.resolve(action()).then(loop);
}
return Promise.resolve().then(loop);
}
// Or...
var promiseWhile = Promise.method(function(condition, action) {
if (!condition()) return;
return action().then(promiseWhile.bind(null, condition, action));
});
/// PAEz - here it is with a delay function
function promiseWhile(predicate, action, delay) {
function wait() {
if (delay) return new Promise(function(resolve, reject) {
window.setTimeout(resolve, delay);
});
else return;
}
function loop() {
if (!predicate()) return;
return Promise.resolve(action()).then(wait).then(loop);
}
return Promise.resolve().then(loop);
}
// test
var counter = 0;
function action() {
return new Promise(function(resolve, reject) {
console.log(counter);
resolve();
})
}
function cond() {
if (counter++ < 10) return true;
return false;
}
promiseWhile(cond, action, 500)
.then(function() {
console.log('done')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment