-
-
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
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
/* | |
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