Home >Web Front-end >JS Tutorial >Is Awaiting a Promise Chain in Angular 6 a Code Smell?

Is Awaiting a Promise Chain in Angular 6 a Code Smell?

DDD
DDDOriginal
2024-11-20 03:02:02302browse

Is Awaiting a Promise Chain in Angular 6 a Code Smell?

Awaiting a Promise Chain: Is It a Pitfall?

In Angular 6, developers have been advised against using the following code:

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

The concern is not that it is useless to await a promise chain - as long as someFunction() does return a promise, both snippets work the same. The problem lies elsewhere.

The confusion arises from mixing async programming styles. Async functions, introduced in ES2017, introduce the await keyword. When await is used inside an async function, it pauses the execution of the function and waits for the promise to resolve. This simplifies async programming and makes it easier to read and understand code.

On the other hand, promise chaining is an older approach to async programming. It involves using .then() to chain multiple promises together. While this approach is still valid, it can be confusing when mixed with await.

For instance, if you want to add another promise call at the location of the console.log() call or conditionally return from the function, the semantics become unclear. Can you use await in the callback like elsewhere in the function? Do you need to return the result from the .then() callback? Is it even possible to return from the outer function?

To avoid these complications, it is recommended to stick to one async programming style, preferably using await for consistency. By doing so, you can simplify your code and reduce the risk of introducing bugs. The more concise and clean version would be:

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

The above is the detailed content of Is Awaiting a Promise Chain in Angular 6 a Code Smell?. 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