Advertisement
coombesy

nodejs chainging, whats going wrong

Jan 7th, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env node
  2.  
  3. var fs = require('fs')
  4.  
  5. function Queue() {
  6.  
  7.   // store your callbacks
  8.   this._methods = [];
  9.  
  10.   // keep a reference to your response
  11.   this._response = null;
  12.  
  13.   // all queues start off unflushed
  14.   this._flushed = false;
  15. }
  16.  
  17.  
  18.  
  19. Queue.prototype = {
  20.  
  21.   // adds callbacks to your queue
  22.   add: function(fn) {
  23.  
  24.     // if the queue had been flushed, return immediately
  25.     if (this._flushed) {
  26.       fn(this._response);
  27.  
  28.     // otherwise push it on the queue
  29.     } else {
  30.  
  31.       this._methods.push(fn);
  32.     }
  33.   },
  34.  
  35.  
  36.  
  37.   flush: function(resp) {
  38.  
  39.     // note: flush only ever happens once
  40.     if (this._flushed) {
  41.  
  42.       return;
  43.     }
  44.  
  45.     // store your response for subsequent calls after flush(
  46.     this._response = resp;
  47.  
  48.     // mark that it's been flushed
  49.     this._flushed = true;
  50.  
  51.     // shift 'em out and call 'em back
  52.     while (this._methods[0]) {
  53.  
  54.       this._methods.shift()(resp);
  55.     }
  56.   }
  57. };
  58.  
  59.  
  60. var foo = function(){
  61.  
  62.     this.method1 = function(){
  63.         console.log('method1 called')
  64.         return this
  65.     }
  66.  
  67.     this.method2 = function(){
  68.         fs.readFile('./lib/jsondb', function(){
  69.             console.log('method2 called')          
  70.         })
  71.         return this
  72.     }
  73.  
  74.     this.method3 = function(){
  75.         console.log('method3 called')
  76.         return this
  77.     }
  78. }
  79.  
  80. var o = new foo()
  81. var queue = new Queue()
  82.  
  83. var front = {
  84.  
  85.     "one" : function(){
  86.         queue.add(o.method1)
  87.         queue.flush()
  88.         return this
  89.     },
  90.  
  91.     "two" : function(){
  92.         queue.add(o.method2)
  93.         return this
  94.     },
  95.     "three" : function(){
  96.         queue.add(o.method3)
  97.         return this
  98.     }
  99. }
  100.  
  101. front.one()
  102.     .two()
  103.     .three()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement