Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env node
- var fs = require('fs')
- function Queue() {
- // store your callbacks
- this._methods = [];
- // keep a reference to your response
- this._response = null;
- // all queues start off unflushed
- this._flushed = false;
- }
- Queue.prototype = {
- // adds callbacks to your queue
- add: function(fn) {
- // if the queue had been flushed, return immediately
- if (this._flushed) {
- fn(this._response);
- // otherwise push it on the queue
- } else {
- this._methods.push(fn);
- }
- },
- flush: function(resp) {
- // note: flush only ever happens once
- if (this._flushed) {
- return;
- }
- // store your response for subsequent calls after flush(
- this._response = resp;
- // mark that it's been flushed
- this._flushed = true;
- // shift 'em out and call 'em back
- while (this._methods[0]) {
- this._methods.shift()(resp);
- }
- }
- };
- var foo = function(){
- this.method1 = function(){
- console.log('method1 called')
- return this
- }
- this.method2 = function(){
- fs.readFile('./lib/jsondb', function(){
- console.log('method2 called')
- })
- return this
- }
- this.method3 = function(){
- console.log('method3 called')
- return this
- }
- }
- var o = new foo()
- var queue = new Queue()
- var front = {
- "one" : function(){
- queue.add(o.method1)
- queue.flush()
- return this
- },
- "two" : function(){
- queue.add(o.method2)
- return this
- },
- "three" : function(){
- queue.add(o.method3)
- return this
- }
- }
- front.one()
- .two()
- .three()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement