diff --git a/src/application.ts b/src/application.ts index 31b86f3..c8246d4 100644 --- a/src/application.ts +++ b/src/application.ts @@ -80,7 +80,8 @@ export class ArtusApplication implements Application { async close(exit = false) { try { - await this.lifecycleManager.emitHook('beforeClose'); + // reverse emitHook to avoid plugin closed before app hook + await this.lifecycleManager.emitHook('beforeClose', null, true); } catch (e) { throw new Error(e); } diff --git a/src/lifecycle/index.ts b/src/lifecycle/index.ts index f8b69bf..d30b37e 100644 --- a/src/lifecycle/index.ts +++ b/src/lifecycle/index.ts @@ -70,7 +70,7 @@ export class LifecycleManager { } } - async emitHook(hookName: string, payload?: T) { + async emitHook(hookName: string, payload?: T, reverse = false) { if (!this.enable) { return; } @@ -83,6 +83,9 @@ export class LifecycleManager { } // lifecycle hook should only trigger one time this.hookFnMap.delete(hookName); + if (reverse) { + fnList.reverse(); + } for (const hookFn of fnList) { await hookFn({ app: this.app, diff --git a/test/lifecycle.test.ts b/test/lifecycle.test.ts index b1c302a..ed255af 100644 --- a/test/lifecycle.test.ts +++ b/test/lifecycle.test.ts @@ -46,9 +46,9 @@ describe('test/lifecycle.test.ts', () => { 'pluginA_didReady', 'pluginB_didReady', 'app_didReady', - 'pluginA_beforeClose', - 'pluginB_beforeClose', 'app_beforeClose', + 'pluginB_beforeClose', + 'pluginA_beforeClose', ]); }); @@ -84,9 +84,9 @@ describe('test/lifecycle.test.ts', () => { 'pluginA_didReady', 'pluginB_didReady', 'app_didReady', - 'pluginA_beforeClose', - 'pluginB_beforeClose', 'app_beforeClose', + 'pluginB_beforeClose', + 'pluginA_beforeClose', ]); });