From 72977832153b0804d15a5ddf7d3cebdb5e69dcd6 Mon Sep 17 00:00:00 2001 From: harlan Date: Tue, 3 Sep 2024 15:24:45 +1000 Subject: [PATCH] fix(useScriptTriggerElement): reject promises on scope dispose --- .../composables/useScriptTriggerElement.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/runtime/composables/useScriptTriggerElement.ts b/src/runtime/composables/useScriptTriggerElement.ts index 1be08e5e..8507bf61 100644 --- a/src/runtime/composables/useScriptTriggerElement.ts +++ b/src/runtime/composables/useScriptTriggerElement.ts @@ -7,6 +7,7 @@ import { useEventListener, useIntersectionObserver, } from '@vueuse/core' +import { tryOnScopeDispose } from '@vueuse/shared' import type { ElementScriptTrigger } from '../types' export interface ElementScriptTriggerOptions { @@ -23,7 +24,7 @@ export interface ElementScriptTriggerOptions { function useElementVisibilityPromise(element: MaybeComputedElementRef) { let observer: UseIntersectionObserverReturn - return new Promise((resolve) => { + return new Promise((resolve, reject) => { observer = useIntersectionObserver( element, (intersectionObserverEntries) => { @@ -38,9 +39,14 @@ function useElementVisibilityPromise(element: MaybeComputedElementRef) { threshold: 0, }, ) - }).finally(() => { - observer.stop() + tryOnScopeDispose(reject) }) + .catch(() => { + // it's okay + }) + .finally(() => { + observer.stop() + }) } /** @@ -57,16 +63,19 @@ export function useScriptTriggerElement(options: ElementScriptTriggerOptions): P return Promise.resolve() if (!triggers.includes('immediate')) { // TODO optimize this, only have 1 instance of intersection observer, stop on find - return new Promise((resolve) => { + return new Promise((resolve, reject) => { const _ = useEventListener( typeof el !== 'undefined' ? (el as EventTarget) : document.body, triggers, () => { - resolve() _() + resolve() }, { once: true, passive: true }, ) + tryOnScopeDispose(reject) + }).catch(() => { + // it's okay }) } return Promise.resolve()