The short answer is YES; a return value from an async
function always returns a Promise
implicitly. It resolves with whatever the async
function returns, or rejects with whatever the async
function throws. To demonstrate this, let's output the return value of an async
function without await
:
async function foo() { return 'foobar'; } console.log(foo()); // output: Promise {<fulfilled>: "foobar"}
This is also true when the async
function has no return value. In that case, we get a Promise
object resolved with undefined
. For example:
async function foo() {} console.log(foo()); // output: Promise {<fulfilled>: undefined}
Similarly, a rejected Promise
is implicitly returned when an error is thrown inside an async
function. For example:
async function foo() { throw new Error('foobar'); } console.log(foo()); // output: Promise {<rejected>: Error: foobar}
It may also be worth mentioning that returning a Promise
explicitly inside an async
function won't return a Promise
of a Promise
but rather a single Promise
with resolved/rejected value.
Check out our other post if you want to learn more about different states (and fates) of a JavaScript Promise
.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.