InterceptorManager.js 1.2 KB

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