Awaiting Promise Chains: Potential Pitfalls
It has been advised against awaiting promise chains in certain contexts, particularly in Angular 6 applications. This seemingly redundant approach raises questions about its potential consequences.
The Issue with Promise Chaining
The following code snippet exemplifies the anti-pattern in question:
await someFunction().then(result => { console.log(result); });
This code unnecessarily wraps the promise returned by someFunction() in a Promise.then chain before awaiting it.
Alternative Solution
A more concise and straightforward approach is to simply await the promise directly:
const result = await someFunction(); console.log(result);
Why Avoid Promise Chaining?
While both snippets achieve the same result, the first one invites confusion and potential bugs:
Consistency is Key
For the sake of maintaining consistency and avoiding potential pitfalls, it's advisable to prefer the simpler approach of awaiting promises directly. This aligns with the general rule of preferring await over then in asynchronous functions.
Exception to the Rule
While await is generally preferable, there may be exceptions. In certain cases of error handling, promise chaining may provide a cleaner and more concise approach.
The above is the detailed content of Should You Await Promise Chains?. For more information, please follow other related articles on the PHP Chinese website!