public
Last active

Illustrating asynquence "Iterable Sequences"

  • Download Gist
ex1-sync-iteration.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
function step(num) {
return num * 2;
}
 
// set up an iterable sequence
var isq = ASQ.iterable()
.then(step)
.then(step)
.then(step);
 
// synchronously iterate the sequence
for (var seed = 3, ret;
// call `next(..)` on the iterable sequence
// to advance it one iteration
(ret = isq.next(seed)) && !ret.done;
) {
seed = ret.value;
console.log(seed);
}
// 6
// 12
// 24
ex2-async-iteration.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
function step(num) {
return num * 2;
}
 
function iterate(msg) {
// call `next(..)` on the iterable sequence
// to advance it one iteration
var ret = isq.next(msg);
if (!ret.done) {
return ret.value;
}
else {
// break the iteration loop
throw "Iteration complete.";
}
}
 
// set up an iterable sequence
var isq = ASQ.iterable()
.then(step)
.then(step)
.then(step)
.then(function(){
throw "Should not get here!";
})
.or(function(msg){
console.log(msg); // Too big!
});
 
// set up an async loop sequence controller
loop = ASQ()
.or(function(msg){
console.log(msg); // Iteration complete.
console.log(seed); // 24
});
 
// asynchronously iterate the sequence
(function next(msg){
if (msg > 15) {
// throw an error into the iterable
// sequence
sq.throw("Too big!");
}
 
// store seed so we can check it at the end
seed = msg;
 
loop
// wait before proceeding with the iteration
.then(function(done){
setTimeout(done,50);
})
.val(
// inject `msg` into the sequence's
// message stream
msg,
// process the current iteration
iterate,
// start up the next loop iteration
next
);
})(3); // start out msg/step as `3`

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.