
Untitled
By: a guest on
Aug 20th, 2012 | syntax:
None | size: 1.06 KB | hits: 13 | expires: Never
/**
* Chunks a nontrivial operation into a chain of trivial components
* and processes them in the next tick. The result of previous
* chunked operations is passed to the next one.
* @returns void
*/
var Chunk = module.exports = function() {
this.chain = new Array();
this.lastResult = null;
}
var p = Chunk.prototype;
/**
* Adds a callback to the chunk sequence.
* @param Function The callback
* @param Object The context of the callback
*/
p.then = function(callback, context) {
var self = this;
this.chain.push(function(result) {
var result = callback.call(context, self.lastResult);
if(result !== undefined) {
self.lastResult = result;
}
self.go();
});
return this;
};
/**
* Executes the chunk.
* @return void
*/
p.go = function() {
var self = this;
if(this.chain.length > 0) {
process.nextTick(function() {
(self.chain.shift())(self.lastResult);
});
}
};
// Example
new Chunk().then(function() {
return 1 + 2;
}).then(function(result) {
return result + 2;
}).then(function(result) {
console.log('---------', (result + 3));
}).go();