How Await keyword work in situation that it show before every other function

Viewed 31

Question:

I am new in working with async keyword.

Below is the example make me confused. In my understanding, with async keyword, program would wait until the function after await.

So, I expected "Show at the end" would only show up at the very last.

Q: But why does "Show at the end" occur first? Is there a full explanation behind this?

Below is my present code:

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  
  const result = await resolveAfter2Seconds();  //The whole program would stop here until the resolveAfer2Seconds finish
  console.log('calling');
  console.log(result);
}

asyncCall();

console.log('Show at the end') //My expectation is this will only print at the end, as we got a await inisde asyncCall

Here is the result:

Show at the end
resolved
calling
2 Answers

In simple terms:

asyncCall is an asynchronous method itself. Just like resolveAfter2Seconds can be awaited, asyncCall can be awaited too.

But if it is not, then the rest of the execution will continue.

If you want to make use of anything that is returned from resolveAfter2Seconds, you have to write it inside asyncCall after await. Think how convenient it would be to scope together all the code that requires something from an asynchronous call and the rest of the code can continue.

I think it is about the whether you understand the idea of asynchronous.

Here is my new way of looking at the model of asynchronous.

The idea about async function is to make code that requires a certain process to be finished before proceeding separate from the rest of the code that doesn't require any other code to be finished.

And, Await keyword inside async function is to indicate which part of code need to be finished before proceeding.

With such, this make asynchronous robust

Related