Skip to content

Instantly share code, notes, and snippets.

@jrop
Last active August 29, 2015 14:20
Show Gist options
  • Save jrop/539df9b7cd64927c955f to your computer and use it in GitHub Desktop.
Save jrop/539df9b7cd64927c955f to your computer and use it in GitHub Desktop.
Q.while
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