index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const { EventEmitter } = require("events");
  2. class AbortSignal {
  3. constructor() {
  4. this.eventEmitter = new EventEmitter();
  5. this.onabort = null;
  6. this.aborted = false;
  7. this.reason = undefined;
  8. }
  9. toString() {
  10. return "[object AbortSignal]";
  11. }
  12. get [Symbol.toStringTag]() {
  13. return "AbortSignal";
  14. }
  15. removeEventListener(name, handler) {
  16. this.eventEmitter.removeListener(name, handler);
  17. }
  18. addEventListener(name, handler) {
  19. this.eventEmitter.on(name, handler);
  20. }
  21. dispatchEvent(type) {
  22. const event = { type, target: this };
  23. const handlerName = `on${type}`;
  24. if (typeof this[handlerName] === "function") this[handlerName](event);
  25. this.eventEmitter.emit(type, event);
  26. }
  27. throwIfAborted() {
  28. if (this.aborted) {
  29. throw this.reason;
  30. }
  31. }
  32. static abort(reason) {
  33. const controller = new AbortController();
  34. controller.abort();
  35. return controller.signal;
  36. }
  37. static timeout(time) {
  38. const controller = new AbortController();
  39. setTimeout(() => controller.abort(new Error("TimeoutError")), time);
  40. return controller.signal;
  41. }
  42. }
  43. class AbortController {
  44. constructor() {
  45. this.signal = new AbortSignal();
  46. }
  47. abort(reason) {
  48. if (this.signal.aborted) return;
  49. this.signal.aborted = true;
  50. if (reason) this.signal.reason = reason;
  51. else this.signal.reason = new Error("AbortError");
  52. this.signal.dispatchEvent("abort");
  53. }
  54. toString() {
  55. return "[object AbortController]";
  56. }
  57. get [Symbol.toStringTag]() {
  58. return "AbortController";
  59. }
  60. }
  61. module.exports = { AbortController, AbortSignal };