Is it OK to use async/await almost everywhere?

前端 未结 3 1075
梦如初夏
梦如初夏 2021-01-04 18:47

I\'m currently writing small NodeJS CLI tool for personal usage and I\'ve decided to try ES7 async/await feature with Babel.

It\'s a network tool so I obviously hav

3条回答
  •  暖寄归人
    2021-01-04 19:41

    I do requests in many places and I have to mark all these functions as async

    Yes, if all your code is asynchronous, then you'd use async functions everywhere.

    Having all your code be asynchronous makes things complicated though. You have to worry about race conditions everywhere, make sure to handle reentrant functions correctly, and remember that during every await basically anything can happen.

    I mean that almost every function in my code should be async because I need to await a result from other async functions.

    This might not be a best practise. You could try to break down your code into smaller units, most of which are usually not asynchronous. So instead of writing

    async function getXandThenDoY(xargs) {
        let res = await get(xargs);
        …
        return …;
    }
    

    you should consider making two functions

    function doY(res) {
        // synchronous
        …
        return …;
    }
    function getXandDoY(xargs) {
        // asynchronous
        return get(xargs).then(doY);
    }
    /* or, if you prefer:
    async function getXandDoY(xargs) {
        return doY(await get(xargs));
    }
    */
    

提交回复
热议问题