Home >Web Front-end >JS Tutorial >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:
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!