abortsignal-polyfill.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. if (typeof AbortSignal.timeout !== 'function') {
  2. AbortSignal.timeout = (time: number) => {
  3. const controller = new AbortController()
  4. function abort() {
  5. controller.abort(new DOMException('Timed out', 'TimeoutError'))
  6. }
  7. function clean() {
  8. window.clearTimeout(timer)
  9. controller.signal.removeEventListener('abort', clean)
  10. }
  11. controller.signal.addEventListener('abort', clean)
  12. const timer = window.setTimeout(abort, time)
  13. return controller.signal
  14. }
  15. }
  16. if (typeof AbortSignal.any !== 'function') {
  17. AbortSignal.any = (signals: AbortSignal[]) => {
  18. const controller = new AbortController()
  19. // return immediately if any of the signals are already aborted.
  20. for (const signal of signals) {
  21. if (signal.aborted) {
  22. controller.abort(signal.reason)
  23. return controller.signal
  24. }
  25. }
  26. function abort() {
  27. controller.abort()
  28. clean()
  29. }
  30. function clean() {
  31. for (const signal of signals) {
  32. signal.removeEventListener('abort', abort)
  33. }
  34. }
  35. // abort the controller (and clean up) when any of the signals aborts
  36. for (const signal of signals) {
  37. signal.addEventListener('abort', abort)
  38. }
  39. return controller.signal
  40. }
  41. }
  42. export default null // show that this is a module