Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 20th, 2012  |  syntax: None  |  size: 1.06 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. /**
  2.  * Chunks a nontrivial operation into a chain of trivial components
  3.  * and processes them in the next tick.  The result of previous
  4.  * chunked operations is passed to the next one.
  5.  * @returns void
  6.  */
  7. var Chunk = module.exports = function() {
  8.         this.chain = new Array();
  9.         this.lastResult = null;
  10. }
  11.  
  12. var p = Chunk.prototype;
  13.  
  14. /**
  15.  * Adds a callback to the chunk sequence.
  16.  * @param       Function        The callback
  17.  * @param       Object          The context of the callback
  18.  */
  19. p.then = function(callback, context) {
  20.         var self = this;
  21.         this.chain.push(function(result) {
  22.                 var result = callback.call(context, self.lastResult);
  23.                 if(result !== undefined) {
  24.                         self.lastResult = result;
  25.                 }
  26.                 self.go();
  27.         });
  28.         return this;
  29. };
  30.  
  31. /**
  32.  * Executes the chunk.
  33.  * @return      void
  34.  */
  35. p.go = function() {
  36.         var self = this;
  37.         if(this.chain.length > 0) {
  38.                 process.nextTick(function() {
  39.                         (self.chain.shift())(self.lastResult);
  40.                 });
  41.         }
  42. };
  43.  
  44. // Example
  45.  
  46. new Chunk().then(function() {
  47.         return 1 + 2;
  48. }).then(function(result) {
  49.         return result + 2;
  50. }).then(function(result) {
  51.         console.log('---------', (result + 3));
  52. }).go();