Skip to content

Instantly share code, notes, and snippets.

@willconant
Created March 11, 2010 20:46
Show Gist options
  • Save willconant/329632 to your computer and use it in GitHub Desktop.
Save willconant/329632 to your computer and use it in GitHub Desktop.
Flow-JS Serial Sum Example 2
var sys = require('sys');
var flow = require('./flow')
// this is a simple async function for adding an amount to a running total
var currentSum = 0;
function addToSum(amountToAdd, callback) {
setTimeout(function() {
currentSum += amountToAdd;
callback();
}, 100);
}
// this is a nifty nittle re-usable serial forEach function built with some flow magic
var flowForEach = flow.define(
function(items, job, callback) {
this.items = items;
this.curItem = 0;
this.job = job;
this.callback = callback;
this();
},function() {
if (this.curItem >= this.items.length) {
this();
}
else {
this.nextBlockIdx -= 1;
this.curItem += 1;
this.job(this.items[this.curItem - 1]);
}
},function() {
this.callback();
}
);
// this is the array we'd like to execute addToSum on in serial
var values = [5, 7, 1, 3];
// flowForEach takes an array-like object, a function to be applied for each,
// and a function to be called when the job is done.
// The value of "this" in both functions is the flowState, just like in a normal flow.
flowForEach(values, function(val) {
addToSum(val, this)
},function() {
sys.puts("The sum is finally: " + currentSum)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment