`await` vs `.then()` : order of execution

48 views Asked by At

I'm trying to understand the order of execution of JavaScript promises. In the following code, thenFn() is invoked after awaitFn(), but thenFn() still executes(complete the task) first. Can someone explain why this happens?

const thenPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Resolved!: then');
    }, 200);
});

const awaitPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Resolved!: await');
    }, 200);
});

async function awaitFn() {
    console.log(await awaitPromise);
}

function thenFn() {
    thenPromise.then((res) => console.log(res));
}

awaitFn();
thenFn();

It is noteworthy that, I declare the thenPromise before awaitPromise. If I declare awaitPromise first I get the expected output.

Thanks.

Expected Output:
Resolved!: await
Resolved!: then

Actual Output:
Resolved!: then
Resolved!: await

0

There are 0 answers