简体   繁体   中英

When does async function actually return a pending promise?

I googled the question so many times but the only answer I see to this question is:

Async function always returns a promise

but nowhere have I found anything that answers when does that actually happen.

Is it as soon as it goes into the async function or as soon as it encounters the first await keyword?

I have just written this piece of code:

async function main() {
  console.log(true);
  let p = await new Promise(r => setTimeout(r, 2000, 100));
  return p;
}
async function f() {
  inner(await main())

  function inner(d) {
    console.log(d + 10)
  }

  console.log('done')
}

f();

The most important line is:

inner(await main())

main() will be executed first because of the higher priority a function call has in the precedence table and as async function returns a promise, it returns a pending promise!

But to return that, we must execute the main() first, so it goes into the main execution context and sees the console.log(true);

Now is that where the pending promise is returned by the main() ?

Or it will log that and then it'll reach the await keyword and that's when it'll return a pending promise?

What if this was our code:

async function main() {
  (function thatTakes30SecondsToFinish() {
    // some time consuming task
  }())
  let p = await new Promise(r => setTimeout(r, 2000, 100));

  return p;
}

Now in this case, will this main() in this line inner(await main()) immediately return a pending promise or it'll take 30 seconds before returning a pending promise?

Now my guess is:

This line inner(await main()) will immediately return a pending promise but the code inside main() will continue to execute until it gets to the first await keyword, is that correct?

An asynchronous function runs synchronously till it reaches the first await (or the end of the function). Then it returns a new unresolved Promise, that will be resolved somewhen later when the function finished execution. The execution of the asynchronous function then halts, and synchronous execution of the code that called the async function continues.

this line inner(await main()) will immediately return a pending promise but the code inside main() will continue to execute until it gets to the first await keyword, is that correct?

No. First main() will be executed synchronously till the code inside the async main function reaches an await , then it'll return a promise and execution of f continues. As then the await gets reached f also itself returns a new Promise and stops execution.

Semantic details can be found in the specification .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM