javascriptasync-awaitshort-circuit-evaluation

Does JS short-curcuit evaluation work with async/await?


It's well known that in this snippet, if getFirst() returns truthy value, getSecond() is not evaluated:

const result = getFirst() || getSecond();

However, I'm curious if the same holds for async functions:

const result = (await getFirstAsync()) || (await getSyncAsync());

Does it launch the second promise, or waits for the first to get resolved first?


Solution

  • This is trivial to test.

    function getFirstAsync() {
        return new Promise(res => {
            console.log("getFirstAsync");
            res(true);
        });
    }
    
    function getSyncAsync() {
        return new Promise(res => {
            console.log("getSyncAsync");
            res(false);
        });
    }
    
    (async function () {
    
        const result = (await getFirstAsync()) || (await getSyncAsync());
        console.log({result});
    
    })();

    The second function is not called.