Skip to content

Instantly share code, notes, and snippets.

@spion
Last active October 20, 2016 12:12
Show Gist options
  • Save spion/8009559 to your computer and use it in GitHub Desktop.
Save spion/8009559 to your computer and use it in GitHub Desktop.
//jslint: es6 true
var Promise = require('bluebird');
var Continue = {}; // unique
var again = _ => Continue;
var repeat = fn => Promise.try(fn, again)
.then(val => val === Continue && repeat(fn) || val);
// Example 1
var flipCoin = probability => Math.random() < probability;
var pBlah = repeat(again =>
Promise.delay(1000)
.then(_ => console.log("Hello"))
.then(_ => flipCoin(0.9) && again()
|| "blah"));
pBlah.then(console.log)
// Example 2
var orEnd = _ => _;
var pipe = (source, destination) =>
repeat(again =>
source.read()
.then(data => destination.write(data))
.then(again, orEnd)
// Example 3
var sum = 0, stop = 10;
repeat(again => {
if (sum < stop)
return Promise.delay(250)
.then(_ => console.log(++sum))
.then(again));
})
.then(_ => console.log("Done"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment