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) |