javascript - Utilizzo di Async Event Listener con il modulo EventEmitter di Nestjs e funzioni Serverless
Sto cercando di implementare un worker asincrono con una funzione lambda serverless con l'aiuto del modulo EventEmitter di NestJS.
Il gestore viene invocato al momento dell'emissione di un evento, ma la funzione si chiude prima della chiamata async/await.
Ho provato a usare sia le funzioni emit che emitAsync e diversi argomenti per @OnEvent(AccountEvents.NEW_ACCOUNT, {async:true, promisify:true})
Snippet del produttore
public async execute(event: EventDetail): Promise<void> {
await this.eventEmitter.emitAsync(AccountEvents.NEW_ACCOUNT, event);
}
Estratto dell'ascoltatore
@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);
});
}
Output previsto: tutte e 3 le dichiarazioni di log Output effettivo: solo la prima dichiarazione di log (Log1)
Risposta n. 1
Apportare le modifiche come segue funziona. Fondamentalmente dobbiamo passare { async: true, promisify: true } all'annotazione @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 });
}
