Short note on async function

There are many explanations online on what JavaScript async function means. It can get very complicated and confusing. However, there are actually just two things to remember.

1. An async function allows the use of await inside

Pretty self-explanatory.

2. An async function will return a Promise if the return value is not already a Promise

This one needs a little explanation. Let’s modify the example from MDN:

Here we can see asyncReturn1  is trying to return the value resolved from the  promise, while asyncReturn2  is trying to return the promise itself.

However, in the end, the values returned from both are of type  Promise. This is because  asyncReturn1 will implicitly wrap the return value with a Promise.

Also, note that the two Promises returned in result1 and result2 are not the same object despite having the same resolved value. This is because result1 is the implicit Promise being wrapped around the return value, whereas result2 is the original promise.

Leave a Reply