Within Angular 6, you may have encountered the notion that the following pattern is discouraged:
await someFunction().then(result => { console.log(result); });
Initially, this may seem puzzling as it essentially performs the same task as:
const result = await someFunction(); console.log(result);
The latter is generally considered more concise and preferred, but the question arises: why is awaiting a promise chain potentially problematic?
While the above snippets may appear equivalent, there are subtle differences that can introduce risks:
1. Mixed Styles:
Combining synchronous (await) and asynchronous (then) approaches can lead to confusion and mix-ups. This can result in inconsistent code and possible bugs.
2. Complex Control Flow:
As code becomes more complex, adding another promise call within a then callback can introduce a range of new scenarios. It's unclear if you can use await within the callback, how to handle conditional returns, or whether it's possible to return from the outer function. These uncertainties can lead to unexpected behavior and code defects.
To enhance readability, maintainability, and prevent bugs, it's advisable to avoid mixing promise chains with await. Embrace a consistent approach where you utilize await throughout your async functions.
By adhering to this guideline, you can ensure clarity, minimize confusion, and improve the overall quality of your codebase.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3