Last active
August 29, 2015 14:23
-
-
Save cameronwp/7c5704d89202cfdb8562 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Inspired by http://www.dustindiaz.com/async-method-queues | |
// also helpful http://www.mattgreer.org/articles/promises-in-wicked-detail/ | |
function Queue() { | |
this._methods = []; | |
this._flushing = false; | |
} | |
Queue.prototype = { | |
add: function(fn) { | |
this._methods.push(fn); | |
if (!this._flushing) { | |
this.step(); | |
} | |
}, | |
step: function(resp) { | |
var self = this; | |
if (!this._flushing) { | |
this._flushing = true; | |
} | |
function executeInPromise (fn) { | |
return new Promise(function (resolve, reject) { | |
if (fn) { | |
var ret = fn(); | |
} | |
resolve(ret); | |
}); | |
} | |
executeInPromise(this._methods.shift()).then(function (resolve) { | |
if (self._methods.length > 0) { | |
self.step(); | |
} | |
}) | |
} | |
}; | |
function Test () { | |
this.letter = 'a'; | |
this.queue = new Queue; | |
} | |
Test.prototype.asyncMethod = function (letter) { | |
var self = this; | |
this.queue.add(function() { | |
console.log('async start time ' + Date.now()); | |
return new Promise(function (resolve, reject) { | |
setTimeout(function () { | |
self.letter = letter; | |
console.log('async end time ' + Date.now()); | |
resolve(); | |
}, 1000) | |
}) | |
}); | |
return this; | |
}; | |
Test.prototype.syncMethod = function (letter) { | |
var self = this; | |
this.queue.add(function () { | |
console.log('sync start time ' + Date.now()); | |
self.letter = letter; | |
console.log('sync end time ' + Date.now()); | |
}) | |
return this; | |
}; | |
var test = new Test; | |
test.asyncMethod('b').asyncMethod('c').syncMethod('d').asyncMethod('e').syncMethod('f') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment