diff --git a/ts/sveltelib/lifecycle-hooks.ts b/ts/sveltelib/lifecycle-hooks.ts index c05d714f0..9a4f1c7f1 100644 --- a/ts/sveltelib/lifecycle-hooks.ts +++ b/ts/sveltelib/lifecycle-hooks.ts @@ -11,8 +11,8 @@ type ComponentAPIDestroy = (api: T) => void; type SetLifecycleHooksAction = (api: T) => void; export interface LifecycleHooks { - onMount(callback: ComponentAPIMount): Callback; - onDestroy(callback: ComponentAPIDestroy): Callback; + onMount(callback: ComponentAPIMount): Callback | Promise; + onDestroy(callback: ComponentAPIDestroy): Callback | Promise; } /** @@ -27,22 +27,25 @@ function lifecycleHooks(): [LifecycleHooks, T[], SetLifecycleHooksAction { - const cleanups: Callback[] = []; + const cleanups: Promise[] = []; - for (const callback of mountCallbacks) { - const cleanup = callback(api); - - if (cleanup) { - cleanups.push(cleanup); - } + for (const mountCallback of mountCallbacks) { + // Promise.resolve doesn't care whether it's a promise or sync callback + cleanups.push( + Promise.resolve(mountCallback).then((callback) => { + return callback(api); + }), + ); } // onMount seems to be called in reverse order instances.unshift(api); - return () => { - for (const cleanup of cleanups) { - cleanup(); + return async () => { + for (const cleanup of await Promise.all(cleanups)) { + if (cleanup) { + cleanup(); + } } }; }); @@ -50,8 +53,10 @@ function lifecycleHooks(): [LifecycleHooks, T[], SetLifecycleHooksAction { removeItem(instances, api); - for (const callback of destroyCallbacks) { - callback(api); + for (const destroyCallback of destroyCallbacks) { + Promise.resolve(destroyCallback).then((callback) => { + callback(api); + }); } }); }