Search code examples
javascriptasynchronousasync-awaites6-promise

Asynchronous code executing sequentially after wait instead of showing console output immediately


Here is my sample code:

async function counter() {
    console.log('1');

    let next = new Promise((resolve) => {setTimeout(() => resolve(3), 5000)});

    let three = await next;

    console.log('2');
    console.log(three)
}

counter();

The accepted answer on this question says that

When you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before it finishes.

What I understand from this is that 2 should be logged to the console immediately since the function is asynchronous and it shouldn't wait for another task (the promise) to finish (resolve).

However, what I see is that both 2 and 3 are logged together in the console after a wait of 5 seconds. Isn't that what a synchronous function would do based on the above text from the accepted answer?

Thanks.


Solution

  • The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

    You can read more about Await Here

    And you can read more about this acccepted answer here

    What happens basically is if you used await inside your async function, it causes to wait for it until promise is resolved. but outside of that function will still run in parallel to this function.