Asynchronous code in node - avoid redundant usage of async / await

Viewed 318

I have a question about the usage of async / await in a Node.js project wrote in typescript.

We have a chain of functions all with async and await. And my question is:

Could we avoid all these async / await?

   const processed = await this.processMessage(content);

   async processMessage(message): Promise<Boolean> {
     processed = await this.process(message.data);
     return processed;
   }

   async process(data): Promise<Boolean> {
     // some async action with an await that returns a boolean, i.e. delete in database
   } 

And do

   const processed = this.processMessage(content);

   processMessage(message): Boolean {
     processed = this.process(message.data);
     return processed;
   }

   process(data): Boolean {
     // some async action i.e. delete in database
   } 

Are all these async await necessary throughout the code? Or in a case like this where we await for every asynchronous step we could use the second option instead?

1 Answers

If all that processMessage is doing is extracting the data property out of message, you can just forward the promise generated by process and not await the intermediate result.

processMessage(message): Promise<Boolean> {
  return this.process(message.data);
}
Related