Featured Image
Featured Image

Async / Await — Return values

When reading async / await code you come across different styles of returning a value in an async function.

Some just return the plain value:

Others return a promise:

While the third group don’t just use and return a Promise, they await it:

So, you might wonder what the correct way to do this is, or if there even is a difference. But there is no right way to do it, in fact the behavior is exactly the same in all three cases. The important thing is that **async functions always return a Promise**`.

the return value of an async function is implicitly wrapped in Promise.resolve. — MDN

So if you chain a then on the Promise of any of these functions (or await these functions if you want to use async/await), it will only be called once the (implicitly wrapped) Promise is resolved.

Without needing to understand how exactly async / await is transpiled to ES5, intuitively, the second example test2, returning a Promise instead of just the value, looks more like this after conversion:

However the inner Promise is automatically unwrapped, so in the end it again returns just a single Promise resolving to 5. The way to use any of these functions is the same.

Originally published at cmichel.io

Medium Clap
Medium Clap

Written by

Full Stack Software Engineer #javascript #EOS. Into Recreational Math / CS 🤯 Just message me about anything, my mind is open.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store