18abce9b2e976b2d2744ac1e7e35c999404e6acf4c143d62b4c1ceacfa0daf5e3355f3cd6e3b2d4097976e427815bd35cc87d2d5f00063334683fdcebfc063 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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, options) {
  15. this.handlers.push({
  16. fulfilled: fulfilled,
  17. rejected: rejected,
  18. synchronous: options ? options.synchronous : false,
  19. runWhen: options ? options.runWhen : null
  20. });
  21. return this.handlers.length - 1;
  22. };
  23. /**
  24. * Remove an interceptor from the stack
  25. *
  26. * @param {Number} id The ID that was returned by `use`
  27. */
  28. InterceptorManager.prototype.eject = function eject(id) {
  29. if (this.handlers[id]) {
  30. this.handlers[id] = null;
  31. }
  32. };
  33. /**
  34. * Clear all interceptors from the stack
  35. */
  36. InterceptorManager.prototype.clear = function clear() {
  37. if (this.handlers) {
  38. this.handlers = [];
  39. }
  40. };
  41. /**
  42. * Iterate over all the registered interceptors
  43. *
  44. * This method is particularly useful for skipping over any
  45. * interceptors that may have become `null` calling `eject`.
  46. *
  47. * @param {Function} fn The function to call for each interceptor
  48. */
  49. InterceptorManager.prototype.forEach = function forEach(fn) {
  50. utils.forEach(this.handlers, function forEachHandler(h) {
  51. if (h !== null) {
  52. fn(h);
  53. }
  54. });
  55. };
  56. module.exports = InterceptorManager;