1

This question confused me a long time so I decide to ask for help, I believe there is no certain answer, it could be an open discussion.

If one of my function:

  1. Returns a promise
  2. Do not need to await any other functions
  3. Do not create promise itself, it just return a promise returned by another function
  4. Do not call then or catch on promises so it does not involve further async flows

Should this function be async?

For example:

async function updateUser(user) {
    return await fetch('/some/url', {body: JSON.stringify(data)});
}

function growUp1(user) {
    user.age++;
    return updateUser(user);
}

async function growUp2(user) {
    user.age++;
    return await updateUser(user);
}

I think the growUp1 is more simple and have neater code with better performance after babel transformation (since less async generators are involved), and growUp2 is more robust when updateUser switches between async and sync.

Should we possibly enforce:

  1. If a function is returning Promise, it MUST be async
  2. If a function depends on an async function, it MUST be async

or just leave it free for team members?

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
otakustay
  • 11,817
  • 4
  • 39
  • 43
  • This question seems pretty much just asking for opinions. I'm not sure it's the best fit for SO. At the end of the day, the answer is do whatever you feel is best. – loganfsmyth Jun 02 '15 at 16:39

1 Answers1

1

I wouldn't make it an async function. That the normal function returns a promise still should be properly documented of course.

An important thing to consider is that

async function f(x) {
    return await x;
}

is not exactly the identity function - it's the Promise.resolve function actually. If you await an x promise and return the result, you're not getting back x, but a new promise actually. This does incur some overhead (although it is unlikely to be significant).

Should we possibly enforce …

That depends on your team. If you agree to make the async keyword a marker for promise-returning functions, and you want to be consistent about that, then just include it in your style guide and follow that.

I personally don't think it's a good idea, and you shouldn't be dogmatic about it. Use async only where appropriate.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375