Created
August 10, 2017 19:50
-
-
Save wilmoore/cf49bf3a5fce0297f406852d72f8af90 to your computer and use it in GitHub Desktop.
Promise loop (can use as a long-running worker) with predicate.
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
/** | |
* 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