queue.js 941B

123456789101112131415161718192021222324252627282930313233343536
  1. var Q = require("./q");
  2. module.exports = Queue;
  3. function Queue() {
  4. var ends = Q.defer();
  5. var closed = Q.defer();
  6. return {
  7. put: function (value) {
  8. var next = Q.defer();
  9. ends.resolve({
  10. head: value,
  11. tail: next.promise
  12. });
  13. ends.resolve = next.resolve;
  14. },
  15. get: function () {
  16. var result = ends.promise.get("head");
  17. ends.promise = ends.promise.get("tail");
  18. return result.fail(function (error) {
  19. closed.resolve(error);
  20. throw error;
  21. });
  22. },
  23. closed: closed.promise,
  24. close: function (error) {
  25. error = error || new Error("Can't get value from closed queue");
  26. var end = {head: Q.reject(error)};
  27. end.tail = end;
  28. ends.resolve(end);
  29. return closed.promise;
  30. }
  31. };
  32. }