Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active September 26, 2024 14:34
Show Gist options
  • Save wilmoore/cf49bf3a5fce0297f406852d72f8af90 to your computer and use it in GitHub Desktop.
Save wilmoore/cf49bf3a5fce0297f406852d72f8af90 to your computer and use it in GitHub Desktop.
Software Engineering :: Programming :: Languages :: JavaScript :: Example :: Promise loop (can use as a long-running worker) with predicate

Software Engineering :: Programming :: Languages :: JavaScript :: Example :: Promise loop (can use as a long-running worker) with predicate

⪼ Made with 💜 by Polyglot.

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