InterceptorManager.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict'
  2. function InterceptorManager() {
  3. this.handlers = []
  4. }
  5. /**
  6. * Add a new interceptor to the stack
  7. *
  8. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  9. * @param {Function} rejected The function to handle `reject` for a `Promise`
  10. *
  11. * @return {Number} An ID used to remove interceptor later
  12. */
  13. InterceptorManager.prototype.use = function use(fulfilled, rejected) {
  14. this.handlers.push({
  15. fulfilled,
  16. rejected
  17. })
  18. return this.handlers.length - 1
  19. }
  20. /**
  21. * Remove an interceptor from the stack
  22. *
  23. * @param {Number} id The ID that was returned by `use`
  24. */
  25. InterceptorManager.prototype.eject = function eject(id) {
  26. if (this.handlers[id]) {
  27. this.handlers[id] = null
  28. }
  29. }
  30. /**
  31. * Iterate over all the registered interceptors
  32. *
  33. * This method is particularly useful for skipping over any
  34. * interceptors that may have become `null` calling `eject`.
  35. *
  36. * @param {Function} fn The function to call for each interceptor
  37. */
  38. InterceptorManager.prototype.forEach = function forEach(fn) {
  39. this.handlers.forEach((h) => {
  40. if (h !== null) {
  41. fn(h)
  42. }
  43. })
  44. }
  45. export default InterceptorManager