2

I have a small function to learn how async,await and promise workes here.

function delay(ms: number) {
    return new Promise<void>(function(resolve) {
       setTimeout(resolve, ms);
    });
}

async function asyncAwait() {
    console.log("A");

    await delay(1000);
    console.log("B");

    await delay(1000);
    console.log("C");
}

asyncAwait();
console.log("D");

My understanding , the workflow would be like,

call asyncAwait(); first, then print A, then wait for 1s and print B then wait for another 1s and print C at last print D.

but my output is like,

A
D
B
C

I don't know why console.log("D") is displaying second.

can anyone explain the above code ?

thanks in advance

5
  • you are not 'waiting' for the delay Promise and the asyncAwait function with Promise functionality Commented Jul 4, 2019 at 7:42
  • can you explain in details. I am new to ts Commented Jul 4, 2019 at 7:43
  • Reading time: medium.com/@bluepnume/… Commented Jul 4, 2019 at 7:47
  • 1
    You have the explanation in old javascript, in my answer. I have removed the promise part so is more clear to grasp. I hope it help you understand what async await really is Commented Jul 4, 2019 at 7:57
  • thanks. @DanielSan . both answers are working. but your answer is what I expected. you explained it simply. thanks Commented Jul 4, 2019 at 8:00

3 Answers 3

3

It is how asynchronous calls work.

What you think the code execution is like:

function delay(ms: number) {
    return new Promise<void>(function(resolve) {
       setTimeout(resolve, ms);
    });
}

async function asyncAwait() {
    console.log("A");

    await delay(1000);
    console.log("B");

    await delay(1000);
    console.log("C");
}

asyncAwait();   // <-- 1st call
console.log("D");

Then inside that function:

async function asyncAwait() {
    console.log("A");  // <--- 1st print, as it is synchronous

    await delay(1000); // <--- await
    console.log("B");  // <--- 2nd print

    await delay(1000); // <-- await
    console.log("C");  // <-- 3rd print
}

And then finally

function delay(ms: number) {
    return new Promise<void>(function(resolve) {
       setTimeout(resolve, ms);
    });
}

async function asyncAwait() {
    console.log("A");

    await delay(1000);
    console.log("B");

    await delay(1000);
    console.log("C");
}

asyncAwait();
console.log("D"); // <-- last print

BUT, the async function is asynchronous. So all the async calls go into the queue and are processed later.

Hence, first the synchronous calls are executed:

console.log("A");
console.log("D");

And then the async calls.

The await only works inside an async function.

So the function:

async function asyncFunc() {
  console.log("A");

  await delay(1000);
  console.log("B");
}

is roughly equivalent to this:

asyncFunc() {
  console.log('A');
  delay().then(()=> {
     console.log('B');
  });
}

So if you want the console.log("D") to be executed after the async function you should await the asyncFunction. But to use await, you have to be in a async function:

async function asyncFunc2() {
  await asyncAwait();
  console.log("D");
}

asyncFunc2();
Sign up to request clarification or add additional context in comments.

1 Comment

THanks a lot for the detailed explanation. really got it
2

You have to await for asyncAwait() call:


function delay(ms: number) {
    return new Promise<void>(function(resolve) {
       setTimeout(resolve, ms);
    });
}

async function asyncAwait() {
    console.log("A");

    await delay(1000);
    console.log("B");

    await delay(1000);
    console.log("C");
}

async function main() {
    await asyncAwait();
    console.log("D");
}

main();

2 Comments

your answer is working. but when I add one more console.log('E'); after main();, the same doubt came. I wanted to know what happening in my code, how the flow of code . anyhow, thanks for the answer bro.
@SandeepSudhakaran answer is same again. If you add console.log('E') and want it to be executed after main() has completed, then you need to say "wait for main to complete!" by calling it await main();
1

It's behaving like that because under the hood, your code is this:

function equivalentFunction() {
    console.log("A");
    setTimeout(
        function() {
            console.log("B");
            setTimeout(
                function() {
                    console.log("C");
                }
            ,1000)
        }
    ,1000)
}

equivalentFunction();
console.log("D");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.