简体   繁体   English

节点中的异步代码 - 避免重复使用 async / await

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

I have a question about the usage of async / await in a Node.js project wrote in typescript.我有一个关于在 typescript 中编写的 Node.js 项目中使用 async / await 的问题。

We have a chain of functions all with async and await.我们有一连串的函数都带有 async 和 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?或者在这种情况下,我们等待每个异步步骤,我们可以使用第二个选项?

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中提取data属性,您可以只转发process生成的 promise 而无需等待中间结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM