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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
const value = ['resolved']; const promise = new Promise(resolve => { setTimeout(() => { resolve(value); }, 2000); }); async function asyncReturn1() { return await promise; } async function asyncReturn2() { return promise; } async function asyncCall() { var result1 = asyncReturn1(); var result2 = asyncReturn1(); console.log(result1); console.log(result2); // > [object Promise] // > [object Promise] console.log(result1 === result2); // > false var result3 = await result1; var result4 = await result2; console.log(result3); console.log(result4); // > "resolved" // > "resolved" console.log(result3 === result4); // > true } asyncCall(); |
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.