queued-http.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* eslint-disable
  2. max-len,
  3. no-undef,
  4. standard/no-callback-literal,
  5. */
  6. // TODO: This file was created by bulk-decaffeinate.
  7. // Fix any style issues and re-enable lint.
  8. /*
  9. * decaffeinate suggestions:
  10. * DS101: Remove unnecessary use of Array.from
  11. * DS102: Remove unnecessary code created because of implicit returns
  12. * DS207: Consider shorter variations of null checks
  13. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  14. */
  15. define(['../base'], App =>
  16. App.factory('queuedHttp', function($http, $q) {
  17. const pendingRequests = []
  18. let inflight = false
  19. var processPendingRequests = function() {
  20. if (inflight) {
  21. return
  22. }
  23. const doRequest = pendingRequests.shift()
  24. if (doRequest != null) {
  25. inflight = true
  26. return doRequest()
  27. .then(function() {
  28. inflight = false
  29. return processPendingRequests()
  30. })
  31. .catch(function() {
  32. inflight = false
  33. return processPendingRequests()
  34. })
  35. }
  36. }
  37. const queuedHttp = function(...args) {
  38. // We can't use Angular's $q.defer promises, because it only passes
  39. // a single argument on error, and $http passes multiple.
  40. const promise = {}
  41. const successCallbacks = []
  42. const errorCallbacks = []
  43. // Adhere to the $http promise conventions
  44. promise.then = function(callback, errCallback) {
  45. successCallbacks.push(callback)
  46. if (errCallback != null) {
  47. errorCallbacks.push(errCallback)
  48. }
  49. return promise
  50. }
  51. promise.catch = function(callback) {
  52. errorCallbacks.push(callback)
  53. return promise
  54. }
  55. const doRequest = () =>
  56. $http(...Array.from(args || []))
  57. .then((...args) =>
  58. Array.from(successCallbacks).map(cb =>
  59. cb(...Array.from(args || []))
  60. )
  61. )
  62. .catch((...args) =>
  63. Array.from(errorCallbacks).map(cb => cb(...Array.from(args || [])))
  64. )
  65. pendingRequests.push(doRequest)
  66. processPendingRequests()
  67. return promise
  68. }
  69. queuedHttp.post = (url, data) => queuedHttp({ method: 'POST', url, data })
  70. return queuedHttp
  71. }))