InterceptorManager.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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: fulfilled,
  16. rejected: 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