Skip to content

Commit

Permalink
fix: BackgroundTaskHelper should support recursively call (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
killagu authored Feb 2, 2023
1 parent b47d151 commit 368ac03
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
8 changes: 6 additions & 2 deletions core/background-task/src/BackgroundTaskHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
17 changes: 17 additions & 0 deletions core/background-task/test/BackgroundTaskHelper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
});
14 changes: 14 additions & 0 deletions plugin/tegg/test/app/extend/context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
});

0 comments on commit 368ac03

Please sign in to comment.