-1

I was wondering if functions called with the await keyword only run in order if they resolve to promises. If so, how does the interpreter know that these functions are going to resolve to promises and to not run them concurrently?

For example, the following code takes a total of 5 seconds and 'Hello' is logged immediately to the console. All of the await functions seem to run concurrently.

    async function test() {
        function work() {
          console.log("work");
        }

        await setTimeout(work, 5000);
        await setTimeout(work, 1000);
        await setTimeout(work, 5000);
        await setTimeout(work, 1000);
        await console.log("Hello")
      }
J. Doe
  • 59
  • 5

2 Answers2

0

When the interpreter looks at the function itself and sees it's got the async keyword, it knows it will always return a Promise. From the MDN page regarding async functions:

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

esqew
  • 39,199
  • 27
  • 87
  • 126
  • Does awaiting a non-Promise have any detectable effect? – ControlAltDel Apr 05 '22 at 20:11
  • @ControlAltDel I would imagine that's answered in the question you linked in your own answer to this same question, no? https://stackoverflow.com/questions/55262996/does-awaiting-a-non-promise-have-any-detectable-effect TL;DR - not really in most contexts. – esqew Apr 05 '22 at 20:13
  • Just as an FYI :) – ControlAltDel Apr 05 '22 at 20:29
0
  1. I was wondering if functions called with the await keyword only run in order if they resolve to promises.: Does awaiting a non-Promise have any detectable effect?
  2. If so, how does the interpreter know that these functions are going to resolve to promises and to not run them concurrently? Async processes can absolutely run concurrently. If you are making a net or FS request, something else can run in JavaScript while the data is being marshalled
ControlAltDel
  • 32,042
  • 9
  • 48
  • 75