0

Consider the following code snippet:

async function f() {
    console.log("entering");
    for (let i=0;i<=1e9;i++) {}
    console.log("quitting");
}

async function g() {
    console.log("before");
    f();
    console.log("after");
}

g();

I would expect the function g() to call f() without waiting for it to finish. Thus, I would expect the output to be

before
entering
after
quitting

However, g() actually waits for f() to finish. Why does this happen, when f() is supposed to be an async function?

Philipp Imhof
  • 204
  • 1
  • 7
  • 1
    There is no `await` within `f()` that would cause it to run asynchronously. `async` just means that you can use `await` within the function. – phuzi Nov 26 '19 at 14:44
  • You have to use `await` . Check this out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Description – Armedin Kuka Nov 26 '19 at 14:45
  • 1
    It seems that you have some misconceptions about what the `async/await` mechanism means. – Pointy Nov 26 '19 at 14:45
  • 1
    @ArmedinKuka — You can only await a promise. A for loop is not a promise. – Quentin Nov 26 '19 at 14:54
  • @Pointy This is well possible and is mainly the reason for my question... – Philipp Imhof Nov 26 '19 at 15:23
  • @PhilippImhof [here is a pretty good introduction](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) – Pointy Nov 26 '19 at 15:24

0 Answers0