Last active
August 29, 2015 14:20
-
-
Save jrop/539df9b7cd64927c955f to your computer and use it in GitHub Desktop.
Q.while
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
var Q = require('q') | |
Q.while = (conditionCallback, stepCallback) => { | |
var deferredWhile = Q.defer() | |
// | |
// CONDITION | |
// | |
// This is where the condition checking happens: | |
// 1) check the conditional | |
// 2) notify the promise so that it can execute the body | |
// | |
function _whileStep() { | |
return Q.fcall(conditionCallback) | |
.catch(e => { deferredWhile.reject(e) }) | |
.then(result => { | |
if (result) deferredWhile.notify() | |
else deferredWhile.resolve() | |
}) | |
} | |
// | |
// BODY | |
// | |
// This executes the body of the loop, and | |
// then calls again to the 'step' function (try to iterate again) | |
// | |
deferredWhile.promise.progress(() => { | |
Q.fcall(stepCallback) | |
.catch(e => { deferredWhile.reject(e) }) | |
.then(() => _whileStep()) | |
}) | |
// start the loop: | |
_whileStep() | |
return deferredWhile.promise | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment