Home  >  Article  >  Web Front-end  >  Why Is Awaiting a Promise Chain in Angular 6 an Anti-Pattern?

Why Is Awaiting a Promise Chain in Angular 6 an Anti-Pattern?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 03:39:12588browse

Why Is Awaiting a Promise Chain in Angular 6 an Anti-Pattern?

The Perils of Awaiting a Promise Chain

In Angular 6, it is considered an anti-pattern to await a promise chain, as exemplified by the following code:

await someFunction().then(result => {
    console.log(result);
});

While this approach may seem innocuous, it can introduce subtle bugs and reduce maintainability.

Understanding the Issue

Ordinarily, awaiting a promise chain is redundant because someFunction(), if it returns a promise, is already awaiting its resolution. Therefore, the simplified code below achieves the same result:

const result = await someFunction();
console.log(result);

Potential Dangers

However, awaiting a promise chain can lead to unintended consequences:

  • Mixed Styles: Mixing await with then is confusing and hard to maintain.
  • Flow Control: Adding additional promise calls or conditionals within the then callback becomes more complex, introducing potential for errors.
  • Asynchronous Consistency: Async functions should consistently use await for flow control, avoiding the need for then callbacks.

Recommendation

To enhance code clarity and prevent potential issues, it is advisable to adhere to the following guidelines:

  • Prefer Concise Syntax: Use await directly for awaiting promises, avoiding unnecessary promise chaining.
  • Handle Errors Use promise chaining (then and catch) only for error handling when necessary.
  • Maintain Consistency: Stick to await for flow control within async functions to improve readability and maintainability.

The above is the detailed content of Why Is Awaiting a Promise Chain in Angular 6 an Anti-Pattern?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn