async function - await not waiting for promise

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?


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()))()

What you need to understand is that async/await does not make your code run synchronously, but let's you write it as if it is:

In short: The function with async in front of it is literally executed asynchronously, hence the keyword "async". And the "await" keyword wil make that line that uses it inside this async function wait for a promise during its execution. So although the line waits, the whole function is still run asynchronously, unless the caller of that function also 'awaits'...

More elaborately explained: When you put async in front of a function, what is actually does is make it return a promise with whatever that function returns inside it. The function runs asynchronously and when the return statement is executed the promise resolves the returning value.

Meaning, in your code:

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

The function "getResult()" will return a Promise which will resolve once it has finished executing. So the lines inside the getResult() function are run asynchronously, unless you tell the function calling getResult() to 'await' for it as well. Inside the getResult() function you may say it must await the result, which makes the execution of getResult() wait for it to resolve the promise, but the caller of getResult() will not wait unless you also tell the caller to 'await'.

So a solution would be calling either:

getResult().then(result=>{console.log(result)})

Or when using in another function you can simply use 'await' again

async callingFunction(){
    console.log(await(getResult());
}