syncqueue.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // TODO: This file was created by bulk-decaffeinate.
  2. // Sanity-check the conversion and remove this comment.
  3. /*
  4. * decaffeinate suggestions:
  5. * DS101: Remove unnecessary use of Array.from
  6. * DS102: Remove unnecessary code created because of implicit returns
  7. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  8. */
  9. // A synchronous processing queue. The queue calls process on the arguments,
  10. // ensuring that process() is only executing once at a time.
  11. //
  12. // process(data, callback) _MUST_ eventually call its callback.
  13. //
  14. // Example:
  15. //
  16. // queue = require 'syncqueue'
  17. //
  18. // fn = queue (data, callback) ->
  19. // asyncthing data, ->
  20. // callback(321)
  21. //
  22. // fn(1)
  23. // fn(2)
  24. // fn(3, (result) -> console.log(result))
  25. //
  26. // ^--- async thing will only be running once at any time.
  27. module.exports = function(process) {
  28. if (typeof process !== 'function') { throw new Error('process is not a function'); }
  29. const queue = [];
  30. const enqueue = function(data, callback) {
  31. queue.push([data, callback]);
  32. return flush();
  33. };
  34. enqueue.busy = false;
  35. var flush = function() {
  36. if (enqueue.busy || (queue.length === 0)) { return; }
  37. enqueue.busy = true;
  38. const [data, callback] = Array.from(queue.shift());
  39. return process(data, function(...result) { // TODO: Make this not use varargs - varargs are really slow.
  40. enqueue.busy = false;
  41. // This is called after busy = false so a user can check if enqueue.busy is set in the callback.
  42. if (callback) { callback.apply(null, result); }
  43. return flush();
  44. });
  45. };
  46. return enqueue;
  47. };