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:
- Returns a promise
- Do not need to
await
any other functions - Do not create promise itself, it just return a promise returned by another function
- Do not call
then
orcatch
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:
- If a function is returning Promise, it MUST be
async
- If a function depends on an
async
function, it MUST beasync
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?