Is it OK to use async/await almost everywhere?

前端 未结 3 1081
梦如初夏
梦如初夏 2021-01-04 18:47

I\'m currently writing small NodeJS CLI tool for personal usage and I\'ve decided to try ES7 async/await feature with Babel.

It\'s a network tool so I obviously hav

3条回答
  •  星月不相逢
    2021-01-04 19:29

    async/await is sometimes called "contagious" or "viral" (or so it has in the C# world), because in order for it to be effective, it needs to be supported all the way down the call chain. Forcing something asynchronous to act synchronous can lead to unintended results, so you should extend it from the original method all the way down to the top level consumer using it. In other words, if you create or use a type that uses it, that type should also implement it, and so on all the way up the chain. So yes, it's expected that you add async to every function that itself relies on it. Just note, however, you should not add preemptively add async to functions that don't actually implement or need it.

    Just think: If you use async (by awaiting something, I mean), you are async. Avoid squashing an async call into something synchronous.

提交回复
热议问题