Created
August 23, 2013 21:56
-
-
Save neilk/6324428 to your computer and use it in GitHub Desktop.
Recursive iterating with promises; done "manually", and with when/unfold
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
'use strict'; | |
var when = require('when'), | |
delay = require('when/delay'), | |
unfold = require('when/unfold'); | |
function getNumber() { | |
var deferred = when.defer(); | |
deferred.resolve(Math.floor(Math.random() * 10)); | |
return deferred.promise; | |
} | |
function chooseMessage(x) { | |
if (x > 5) { | |
return bigPromise(x); | |
} else { | |
return smallPromise(x); | |
} | |
} | |
function bigPromise(x) { | |
var deferred = when.defer(); | |
deferred.resolve(x + " is big"); | |
return deferred.promise; | |
} | |
function smallPromise(x) { | |
var deferred = when.defer(); | |
deferred.resolve(x + " is small"); | |
return deferred.promise; | |
} | |
function display(x) { | |
return when(console.log(x + "!")); | |
} | |
/* After http://stackoverflow.com/questions/17217736/ by Stuart Knightley (stuartk.com) */ | |
function promiseWhile(condition, body) { | |
var deferred = when.defer(); | |
function loop() { | |
if (!condition()) { | |
return deferred.resolve(); | |
} | |
when(body(), loop, deferred.reject); | |
} | |
process.nextTick(loop); | |
return deferred.promise; | |
} | |
function iteratePromiseWhile() { | |
var i = 0; | |
promiseWhile( function() { return i < 10 }, function() { | |
i++; | |
return when(i) | |
.then(function(i) { console.log("i = " + i); }) | |
.then(getNumber) | |
.then(chooseMessage) | |
.then(display); | |
}).then( | |
function() { console.log('done'); } | |
); | |
} | |
// using when.js' built-in unfold. Weird API but it works. | |
function iterateUnfold() { | |
function unspool(i) { | |
getNumber() | |
.then(chooseMessage) | |
.then(display); | |
return ["did " + i, ++i]; | |
} | |
function until10(i) { | |
return i >= 10; | |
} | |
function handler(val) { | |
console.log("handler " + val); | |
return delay(1000); | |
} | |
console.log("hello"); | |
unfold(unspool, until10, handler, 0).then(function() { | |
console.log("done!"); | |
}); | |
} | |
// iteratePromiseWhile(); | |
iterateUnfold(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment