InterceptorManager.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. * Iterate over all the registered interceptors
  35. *
  36. * This method is particularly useful for skipping over any
  37. * interceptors that may have become `null` calling `eject`.
  38. *
  39. * @param {Function} fn The function to call for each interceptor
  40. */
  41. InterceptorManager.prototype.forEach = function forEach(fn) {
  42. utils.forEach(this.handlers, function forEachHandler(h) {
  43. if (h !== null) {
  44. fn(h);
  45. }
  46. });
  47. };
  48. module.exports = InterceptorManager;