Implicit Promises in Async Functions
In JavaScript, async functions are functions that can asynchronously await a promise to complete and return its value. However, a common misconception is that async functions implicitly return a promise for the value they return.
Understanding the Return Value
While it may appear that async functions implicitly return a promise, this is not entirely accurate. The return value of an async function can be one of two things:
Example with Non-Promise Value:
async function increment(num) { return num + 1; } increment(3).then(num => console.log(num)); // Logs: 4
Here, we return a number from the async function. However, the output is retrieved through .then(), indicating that it is a promise that has been resolved to the value 4.
Explicit Promises:
If we explicitly return a promise from an async function, we receive a promise for that value, not a promise for a promise.
async function increment(num) { return Promise.resolve(num + 1); } increment(3).then(num => console.log(num)); // Logs: 4
Exceptional Cases:
Conclusion
Async functions in JavaScript implicitly wrap non-promise return values in a promise. However, if the return value is already a promise, it is left untouched. This behavior differs from traditional return statements but is consistent with the underlying principles of generators in ES6.
The above is the detailed content of Do Async Functions in JavaScript Always Return Promises?. For more information, please follow other related articles on the PHP Chinese website!