syncqueue.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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') {
  29. throw new Error('process is not a function')
  30. }
  31. const queue = []
  32. const enqueue = function (data, callback) {
  33. queue.push([data, callback])
  34. return flush()
  35. }
  36. enqueue.busy = false
  37. var flush = function () {
  38. if (enqueue.busy || queue.length === 0) {
  39. return
  40. }
  41. enqueue.busy = true
  42. const [data, callback] = Array.from(queue.shift())
  43. return process(data, function (...result) {
  44. // TODO: Make this not use varargs - varargs are really slow.
  45. enqueue.busy = false
  46. // This is called after busy = false so a user can check if enqueue.busy is set in the callback.
  47. if (callback) {
  48. callback.apply(null, result)
  49. }
  50. return flush()
  51. })
  52. }
  53. return enqueue
  54. }