queued-http.js 2.1 KB

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