When should we define a function as async

Gray Zhang otakustay at icloud.com
Wed Jun 3 09:28:30 UTC 2015

This is possibly a code style related question, I studied a little deeper so this is how I currently learned:

If you want a special Promise (subclass or extended), you should not use async function since it casts the return value to a standard Promise

If you want to return a promise and attach callbacks to it (not returning promise that spawns by then), you should not use async

function foo() {
    var waiting = fetchResource();
    // Since this code you should not use async functions
    return waiting;
After all above cases, it is still OK to use none async functions that returns Promise, but it’s quite hard to determines if one method is actual async (with Promise) or sync (immediately return values), so I may preferr to mark all async function async for better read experience

Never write return await xxx;, it seems useless either xxx is a promise or not

Anyway this is not an issue about spec itself, it’s more like an open discussion, thanks for reply :)

Best regards

Gray Zhang

在 2015年6月3日 下午4:18:14, Gruenaum Benjamin (benjamingr at gmail.com) 写到:

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:

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. 

es-discuss mailing list  
es-discuss at mozilla.org  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150603/f1ac824f/attachment-0001.html>

More information about the es-discuss mailing list