From 368ac0343d0d4e96b3768e7fd169b721551d0e4b Mon Sep 17 00:00:00 2001 From: killa Date: Thu, 2 Feb 2023 14:06:02 +0800 Subject: [PATCH] fix: BackgroundTaskHelper should support recursively call (#90) --- .../background-task/src/BackgroundTaskHelper.ts | 8 ++++++-- .../test/BackgroundTaskHelper.test.ts | 17 +++++++++++++++++ plugin/tegg/test/app/extend/context.test.ts | 14 ++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/core/background-task/src/BackgroundTaskHelper.ts b/core/background-task/src/BackgroundTaskHelper.ts index 126c1fa3..6639f9cd 100644 --- a/core/background-task/src/BackgroundTaskHelper.ts +++ b/core/background-task/src/BackgroundTaskHelper.ts @@ -54,16 +54,20 @@ export class BackgroundTaskHelper implements EggObjectLifecycle { if (!this.backgroundTasks.length) return; const { promise: timeout, resolve } = this.sleep(); + const backgroundTasks = this.backgroundTasks.slice(); await Promise.race([ // not block the pre destroy process too long timeout, // ensure all background task are done before destroy the context - Promise.all(this.backgroundTasks), + Promise.all(backgroundTasks), ]); - // always resolve the sleep promise resolve(); + if (this.backgroundTasks.length !== backgroundTasks.length) { + this.backgroundTasks = this.backgroundTasks.slice(backgroundTasks.length); + return this.doPreDestroy(); + } } private sleep() { diff --git a/core/background-task/test/BackgroundTaskHelper.test.ts b/core/background-task/test/BackgroundTaskHelper.test.ts index 536b9670..430a4d3d 100644 --- a/core/background-task/test/BackgroundTaskHelper.test.ts +++ b/core/background-task/test/BackgroundTaskHelper.test.ts @@ -57,4 +57,21 @@ describe('test/BackgroundTaskHelper.test.ts', () => { await helper.doPreDestroy(); }); }); + + describe('recursive fn', () => { + it('should done', async () => { + let runDone = 0; + helper.run(async () => { + await sleep(10); + runDone++; + helper.run(async () => { + await sleep(10); + runDone++; + }); + }); + + await helper.doPreDestroy(); + assert(runDone === 2); + }); + }); }); diff --git a/plugin/tegg/test/app/extend/context.test.ts b/plugin/tegg/test/app/extend/context.test.ts index 4b6b5e20..c1b88ac5 100644 --- a/plugin/tegg/test/app/extend/context.test.ts +++ b/plugin/tegg/test/app/extend/context.test.ts @@ -63,5 +63,19 @@ describe('test/app/extend/context.test.ts', () => { }); assert(backgroundIsDone); }); + + it('recursive runInBackground should work', async () => { + let backgroundIsDone = false; + await app.mockModuleContextScope(async ctx => { + ctx.runInBackground(async () => { + await sleep(100); + ctx.runInBackground(async () => { + await sleep(100); + backgroundIsDone = true; + }); + }); + }); + assert(backgroundIsDone); + }); }); });