-1

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.

Real Noob
  • 1,369
  • 2
  • 15
  • 29
  • 1
    You're `await`ing for the promise to resolve before logging 2 and 3. That's the whole point. – Andy Jun 19 '21 at 05:33
  • The `accepted answer` mean that when code is executed sequentially the code stops execution of the next line until the asynchronous function have finished execution. Once it is finished then it moves to next line – brk Jun 19 '21 at 05:33
  • Thanks @brk. :) I am still confused, this line "When you execute something asynchronously, you can move on to another task before it finishes.". seems to suggest the opposite of stopping execution of next line. – Real Noob Jun 19 '21 at 05:48
  • @RealNoob So put some other code between the `let next = …;` and `let three = await next;` statements. Or also immediately after the `counter();` statement. – Bergi Jun 20 '21 at 21:35

1 Answers1

1

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.

timnaire
  • 116
  • 1
  • 6