Question: Do Async Functions Implicitly Return Promises?
In JavaScript, async functions are declared using the async keyword and are frequently thought to automatically return promises. However, this raises a potential inconsistency: when a non-promise value is explicitly returned, the function appears to wrap the value in a promise.
Answer: All Async Functions Return Promises
The behavior observed is correct: all async functions implicitly return promises. Specifically:
Example:
async function increment(num) { return num + 1; } // Logs 4, as the returned promise resolves to 4. increment(3).then(num => console.log(num));
Wrapping Behavior:
This wrapping behavior is unique to generator functions. For instance, generator functions also return promises, but in a different manner:
function* foo() { return 'test'; } // Logs an object, not "test". console.log(foo()); // Logs 'test' by explicitly calling .next() on the generator function. console.log(foo().next().value);
The above is the detailed content of Do Async Functions Always Return Promises?. For more information, please follow other related articles on the PHP Chinese website!