When should we define a function as async

Gray Zhang otakustay at icloud.com
Wed Jun 3 04:21:24 UTC 2015


I asked it on StackOverflow but they say it is not best fit for SO, so I tried to get some help here

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 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:

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?



Best regards

Gray Zhang


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150603/30025b99/attachment.html>


More information about the es-discuss mailing list