Async Functions: Implicit Promise Return or Explicit Control?
Async functions in JavaScript, denoted by the async keyword, are often said to implicitly return promises. However, a closer examination reveals that the reality is more nuanced.
By default, an async function will indeed return a promise if a promise is not explicitly returned. This means that the following code:
async function getVal() { const result = await doSomethingAsync(); return result; }
is equivalent to:
async function getVal() { const result = await doSomethingAsync(); return Promise.resolve(result); }
However, if you explicitly return a non-promise value, the function will automatically wrap it in a promise. For instance, in the following example:
async function getVal() { return doSomethingNonAsync(); }
getVal will actually return a Promise object containing the result of doSomethingNonAsync().
It's worth noting that this behavior differs from traditional JavaScript functions. When you explicitly return a primitive value from a regular function, it's immediately returned. Async functions, however, always return a promise, wrapping non-promise values as needed.
This may seem inconsistent, but it meshes with the concept of generators in ES6. Generators are functions that don't return the same value as their return statement. Instead, they yield a series of values, which can be iterated over using the yield operator.
For example:
function* getVal() { yield doSomethingAsync(); return 'finished'; } // Logs an object. console.log(getVal()); // Logs 'yikes' and then 'finished'. for (const val of getVal()) { console.log(val); }
The above is the detailed content of Async Functions in JavaScript: Implicit Promise or Explicit Return Value?. For more information, please follow other related articles on the PHP Chinese website!