Skip to content

Instantly share code, notes, and snippets.

@jkpl
Created July 28, 2015 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkpl/c7a9155ad3effc1b06b3 to your computer and use it in GitHub Desktop.
Save jkpl/c7a9155ad3effc1b06b3 to your computer and use it in GitHub Desktop.
Promise based queue
function mkBox() {
var box = {values: [], reads: []};
box.enq = function(value) {
box.values.push(value);
if (box.reads.length > 0) {
box.reads.shift().resolve(box.values.shift());
}
return box;
};
box.deq = function() {
var d = Q.defer();
if (box.values.length > 0 && box.reads.length == 0) {
d.resolve(box.values.shift());
} else {
box.reads.push(d);
}
return d.promise;
};
return box;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment