async function - await not waiting for promise

hg_git picture hg_git · Aug 25, 2017 · Viewed 67.7k times · Source

I'm trying to learn async-await. In this code -

const myFun = () => {
    let state = false;

    setTimeout(() => {state = true}, 2000);

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if(state) {
                resolve('State is true');
            } else {
                reject('State is false');
            }
        }, 3000);
    });
}

const getResult = async () => {
    return await myFun();
}

console.log(getResult());

why am I getting output as -

Promise { <pending> }

Instead of some value? Shouldn't the getResult() function wait for myFun() function resolve it's promise value?

Answer

Ben Fortune picture Ben Fortune · Aug 25, 2017

If you're using async/await, all your calls have to use Promises or async/await. You can't just magically get an async result from a sync call.

Your final call needs to be:

getResult().then(response => console.log(response));

Or something like:

(async () => console.log(await getResult()))()