Is it OK to use async/await almost everywhere?

前端 未结 3 1083
梦如初夏
梦如初夏 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:38

    I had the same question.

    And found a great answer here → ‘Pitfall 3: your whole stack needs to be async’

    No, async/await is not contagious. (I believed the same thing for some time, too)

    You can always treat the result of a sync function like a promise, and you are back to normal.

    From developer.mozilla.org:

    The async function declaration defines an asynchronous function…

    Return value: A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.

    Sample code:

    const log = console.log; // just lazy shorthand
    
    // just to delay, as seen in many places
    function promiseTimeout(time, value) {
        return new Promise(function(resolve, reject) {
            setTimeout(function() { resolve(value); }, time);
        });
    };
    
    // the thing you care about
    async function foo() {
        Promise.resolve('here')
        .then((a) => {log('doing stuff '+a); return 'pear'})
        .then(function(v) {
            return promiseTimeout(1000,v)
        });
    };
    
    // treat async-function like promise:
    foo().then(function(){ log('folling up in main, ')});
    // log('bad end');
    

    gets you:

    doing stuff here
    following up in main
    

    Enabling 'bad end' would show up too early. You can only await stuff it you use await. (And if you do, remember: It's just syntactic sugar, saving you of stuffing your follow-up code into .then() clasuses... nice, but no more than that.)

提交回复
热议问题