Home >Web Front-end >JS Tutorial >Do Async Functions Always Return Promises, Even Without Explicit Returns?

Do Async Functions Always Return Promises, Even Without Explicit Returns?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-17 21:48:12398browse

Do Async Functions Always Return Promises, Even Without Explicit Returns?

Implicit Return of Promises in Async Functions

Contrary to the assumption that async functions return the values of await expressions directly, they actually always return a promise. In cases where an explicit return statement is not present, the value to be returned is automatically wrapped in a promise. This holds true for all return values, including non-promises.

Example:

In this scenario, even though a number is returned, it is still encapsulated within a promise. This is evident when accessing the returned value through the then() method.

Other Cases:

  • Functions with no return statements also implicitly return a promise for an undefined value.
  • Async functions involving await expressions return a promise for the value returned from the await operation.

Exception:

An exception to this rule occurs when a promise is explicitly returned from within an async function. In such cases, the promise is not re-wrapped.

Example:

Conclusion:

While this behavior may deviate from traditional JavaScript return statements, it aligns with the concept of generators in ES6, which do not return the exact value as the return statement.

The above is the detailed content of Do Async Functions Always Return Promises, Even Without Explicit Returns?. 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