javascript - Používanie asynchrónneho poslucháča udalostí s modulom EventEmitter v Nestjs a serverless funkciami
Snažím sa implementovať asynchrónneho pracovníka pomocou serverless lambda funkcie s pomocou modulu EventEmitter v nestjs.
Handler je vyvolaný pri emitovaní udalosti, ale funkcia sa zavrie pred volaním async/await.
Skúšal som používať funkcie emit a emitAsync a rôzne argumenty pre @OnEvent(AccountEvents.NEW_ACCOUNT, {async:true, promisify:true})
Úryvok producenta
public async execute(event: EventDetail): Promise<void> {
await this.eventEmitter.emitAsync(AccountEvents.NEW_ACCOUNT, event);
}
Úryvok poslucháča
@OnEvent(AccountEvents.NEW_ACCOUNT)
public async handleAccountCreatedEvent(event: EventDetail): Promise<void> {
this.logger.log({ message: `Log1: ${AccountEvents.NEW_ACCOUNT} Handler`, event });
const message = await this.testAsync();
this.logger.log({ message });
this.logger.log({ message: 'Log 3: Event Processing Successfuly Completed' });
}
private testAsync(): Promise<string> {
return new Promise(res => {
setTimeout(() => {
res('Log 2: Promise resolved after one sec');
}, 1000);
});
}
Očakávaný výstup: všetky 3 logovacie výpisy Skutočný výstup: iba prvý logovací výpis (Log1)
Odpoveď č. 1
Urobte zmeny nasledovne, funguje to. V podstate musíme odovzdať { async: true, promisify: true } anotácii @onEvent.
@OnEvent(AccountEvents.NEW_ACCOUNT, { async: true, promisify: true })
async handleNewAccountEvent(event: IEvent<RootAccountInterface>): Promise<void> {
const eventDetail: RootAccountInterface = event.data;
this.logger.log({ message: ` ${AccountEvents.NEW_ACCOUNT} Handler`, event });
await this.abc.logNewAccountCreation(eventDetail.accountId);
this.logger.log({ message: ` ${AccountEvents.NEW_ACCOUNT} Handled Successfully`, event });
}
