Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Created August 10, 2017 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilmoore/cf49bf3a5fce0297f406852d72f8af90 to your computer and use it in GitHub Desktop.
Save wilmoore/cf49bf3a5fce0297f406852d72f8af90 to your computer and use it in GitHub Desktop.
Promise loop (can use as a long-running worker) with predicate.
/**
* Hat Tip: https://gist.github.com/victorquinn/8030190#gistcomment-1615901
*/
'use strict'
var Promise = require('bluebird')
var times = 0
function promiseWhile (predicate, action) {
function loop () {
if (!predicate()) {
return
} else {
return Promise.resolve(action()).then(loop)
}
}
return Promise.resolve().then(loop)
}
function isOK () {
return times < 5
}
function work () {
return Promise.delay(1500).then(() => {
times += 1
console.log('hello there')
})
}
promiseWhile(isOK, work)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment