When should we define a function as async

Benjamin Gruenaum benjamingr at gmail.com
Wed Jun 3 08:17:34 UTC 2015


A function needs to be defined `async` if you intend to possibly use the
await keyword inside it.

> If a function is returning Promise, it MUST be async If a function
depends on an async function, it **MUST be async A further question could
be, if one function only contains some simple then calls to promise, should
it become an async function and use await in all possible cases to
eliminate then calls?

No, it's possible to have legitimate use cases where this is not the case,
for example:

```js
async function foo() { ...}  // queries an API

async function bar() { ... } // queries an API

function fooBar() {
    return Promise.all([foo(), bar()]);
}
```

It's a contrived simplified example but the point is you might have
functions that work on promises that should not themselves be `async`.

For example, in your updateUser function, you can remove `async` and
`await` and get the same value (as you observed in growUp1).

To clarify, there is no _semantic_ distinction in your examples between an
async function and a regular function that returns a promise - it's just
syntax sugar - just like generators and regular functions that return
iterables.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150603/bdab8606/attachment.html>


More information about the es-discuss mailing list