async/await always returns promise
Solution 1:
Every async
function returns a Promise
object. The await
statement operates on a Promise
, waiting until the Promise
resolve
s or reject
s.
So no, you can't do console.log
on the result of an async function directly, even if you use await
. Using await
will make your function wait and then return a Promise
which resolves immediately, but it won't unwrap the Promise
for you. You still need to unwrap the Promise
returned by the async
function, either using await
or using .then()
.
When you use .then()
instead of console.log
ging directly, the .then()
method makes the result of the Promise available to you. But you can't get the result of the Promise
from outside the Promise. That's part of the model of working with Promises.
Solution 2:
A function defined with async
always returns a Promise
. If you return any other value that is not a Promise
, it will be implicitly wrapped in a Promise
. The statement const json = await request();
unwraps the Promise
returned by request()
to a plain object { foo: 'bar' }
. This is then wrapped in a Promise
before being returned from getJSON
so a Promise
is what you ultimately get when you call getJSON()
. So to unwrap it, you can either call getJSON().then()
like you've done or do await getJSON()
to get the resolved value.
Solution 3:
Return value of an async function will always be an AsyncFunction Object, which will return a Promise
when called. You can not change that return type. The point of async/await
is to easily wait for other async process to complete inside an async function.