Async Functions in JavaScript
According to Wikipedia, Async/Await is a syntactic feature of programming languages that allows an asynchronous function to be structured in a way similar to an ordinary synchronous function. In this post we will talk about async keyword in JavaScript.
Async keyword can be placed before a function definition. This way we can define an async function in JavaScript.
Async function is a function that executes asynchronously via the JavaScript Event Loop.
Returning Non-Promise Values From An Async Function
The important thing to know about async functions in JavaScript is that async function always returns a promise. If async function returns a non-promise value, then JavaScript automatically wraps it into a promise. A resolved promise with that same value. Let me show what I mean by the following example:
This function returns a string “Hello World”. However, if we invoke sayHelloWorld function, we will get a promise as a result:
As you can see on the screenshot above, sayHelloWorld function returned a resolved promise with the value “Hello World”.
Returning A Promise From An Async Function
If an async function returns something that is already a promise,
then JavaScript will not make any transformations on it. For example, let’s return a promise from an async function:
If we invoke function f and check its return value right away (without waiting 5 seconds), we will notice that this function returns a pending promise.
You can see that variable x contains a pending promise at the moment.
But if we wait 5 seconds and check it again, the promise will be resolved.
As you can see, now variable x contains a resolved promise with the value true. So async function hasn’t made any modifications on the return value this time.
Get Viktor Pyskunov’s stories in your inbox
Join Medium for free to get updates from this writer.
We can also return a rejected promise from an async function.
Then function f will return a rejected promise without any modifications.
As you can see, async function returned the same rejected promise. It didn’t convert it to a resolved promise or anything else. It just returned the promise as it was.
Throwing An Error Inside An Async Function
If an error is thrown inside an async function, this function returns a rejected promise. In this situation PromiseValue will be equal to the Error instance that was thrown.
If we invoke function f, we will get a promise with the PromiseStatus equal to “rejected” and PromiseValue equal to “Error: Some error”.
However, if I return an error (not throw) from an async function, it will convert this error to a resolved promise:
So async keyword ensures that the function returns a promise,
and wraps non-promise values into a promise.






