Why does an async function return a promise even when I return an ordinary value?
Quick answer
An async function always returns a promise. If you write return 7, the caller receives a promise that fulfills with 7, not the number directly. Use await inside another async function to get the fulfilled value, or attach .then() to the promise. For this simple return, an async function is similar to a regular function returning Promise.resolve(7), though the forms are not identical in every detail. [S1]
The question, the details, the next step.
A practical checklist
If a function is declared with
async, treat its call result as a promise.The ordinary value after
returnis what the returned promise fulfills with.Use
await getCount()inside an async function to use the fulfilled value.Use
getCount().then(...)to handle the fulfilled value with a promise handler.Do not assume an async function and a regular function returning
Promise.resolve(value)are identical in every detail.
A few more useful answers
Does `return 7` mean `getCount()` gives me the number 7?
No. The call returns a promise that fulfills with 7; use await or .then() to consume that value. [S1]
Do I need to write `return Promise.resolve(7)` inside an async function?
Not just to wrap an ordinary value: returning 7 from an async function already makes its returned promise fulfill with that value. [S1]
Are an async function returning 7 and a regular function returning `Promise.resolve(7)` exactly equivalent?
They are similar for this comparison, but not identical in every detail. [S1]
Sources
References used for this guide.
- [S1] async function — JavaScript | MDN developer.mozilla.org · Checked
