11import './lib/AppLoadUnit' ;
22import './lib/AppLoadUnitInstance' ;
33import './lib/EggCompatibleObject' ;
4- import { Application } from 'egg' ;
4+ import { Application , Context } from 'egg' ;
5+ import { BackgroundTaskHelper , PrototypeUtil } from '@eggjs/tegg' ;
6+ import { EggPrototype } from '@eggjs/tegg-metadata' ;
57import { EggContextCompatibleHook } from './lib/EggContextCompatibleHook' ;
68import { CompatibleUtil } from './lib/CompatibleUtil' ;
79import { ModuleHandler } from './lib/ModuleHandler' ;
@@ -28,6 +30,29 @@ export default class App {
2830 }
2931
3032 async didLoad ( ) {
33+ const eggRunInBackground = this . app . context . runInBackground ;
34+ this . app . context . runInBackground = function runInBackground ( this : Context , scope : ( ctx : Context ) => Promise < any > ) {
35+ let resolveBackgroundTask ;
36+ const backgroundTaskPromise = new Promise ( resolve => {
37+ resolveBackgroundTask = resolve ;
38+ } ) ;
39+ const newScope = async ( ) => {
40+ try {
41+ await scope ( this ) ;
42+ } finally {
43+ resolveBackgroundTask ( ) ;
44+ }
45+ } ;
46+ Reflect . apply ( eggRunInBackground , this , [ newScope ] ) ;
47+
48+ const proto = PrototypeUtil . getClazzProto ( BackgroundTaskHelper ) ;
49+ const eggObject = this . app . eggContainerFactory . getEggObject ( proto as EggPrototype ) ;
50+ const backgroundTaskHelper = eggObject . obj as BackgroundTaskHelper ;
51+ backgroundTaskHelper . run ( async ( ) => {
52+ await backgroundTaskPromise ;
53+ } ) ;
54+ } ;
55+
3156 await this . app . moduleHandler . ready ( ) ;
3257 this . compatibleHook = new EggContextCompatibleHook ( this . app . moduleHandler ) ;
3358 this . app . eggContextLifecycleUtil . registerLifecycle ( this . compatibleHook ) ;
0 commit comments