Skip to content

Commit 368ac03

Browse files
authored
fix: BackgroundTaskHelper should support recursively call (#90)
1 parent b47d151 commit 368ac03

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

core/background-task/src/BackgroundTaskHelper.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,16 +54,20 @@ export class BackgroundTaskHelper implements EggObjectLifecycle {
5454
if (!this.backgroundTasks.length) return;
5555

5656
const { promise: timeout, resolve } = this.sleep();
57+
const backgroundTasks = this.backgroundTasks.slice();
5758

5859
await Promise.race([
5960
// not block the pre destroy process too long
6061
timeout,
6162
// ensure all background task are done before destroy the context
62-
Promise.all(this.backgroundTasks),
63+
Promise.all(backgroundTasks),
6364
]);
64-
6565
// always resolve the sleep promise
6666
resolve();
67+
if (this.backgroundTasks.length !== backgroundTasks.length) {
68+
this.backgroundTasks = this.backgroundTasks.slice(backgroundTasks.length);
69+
return this.doPreDestroy();
70+
}
6771
}
6872

6973
private sleep() {

core/background-task/test/BackgroundTaskHelper.test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,21 @@ describe('test/BackgroundTaskHelper.test.ts', () => {
5757
await helper.doPreDestroy();
5858
});
5959
});
60+
61+
describe('recursive fn', () => {
62+
it('should done', async () => {
63+
let runDone = 0;
64+
helper.run(async () => {
65+
await sleep(10);
66+
runDone++;
67+
helper.run(async () => {
68+
await sleep(10);
69+
runDone++;
70+
});
71+
});
72+
73+
await helper.doPreDestroy();
74+
assert(runDone === 2);
75+
});
76+
});
6077
});

plugin/tegg/test/app/extend/context.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,5 +63,19 @@ describe('test/app/extend/context.test.ts', () => {
6363
});
6464
assert(backgroundIsDone);
6565
});
66+
67+
it('recursive runInBackground should work', async () => {
68+
let backgroundIsDone = false;
69+
await app.mockModuleContextScope(async ctx => {
70+
ctx.runInBackground(async () => {
71+
await sleep(100);
72+
ctx.runInBackground(async () => {
73+
await sleep(100);
74+
backgroundIsDone = true;
75+
});
76+
});
77+
});
78+
assert(backgroundIsDone);
79+
});
6680
});
6781
});

0 commit comments

Comments
 (0)