2

I always wondered at first what does await does and with experience i slowly started to understand why but after some after i started testing an api that needed to be awaited (mathjs), i had a question. Why does "await" always need an "async" ?

I mean why can't we use await alone for example whenever javascript see this

const result = await justa.functiOn()

it will read it like this :

async function t(){
const result = await justa.functiOn()
}
t()

That would be useful, save time and errors.

I don't need an answer to fix an error i have but just to understand more javascript because i've been searching in many websites but nothing did help me understand.. They only repeated that await needed 'async' ;-;

And i know i can just us an async function englobing everything together. Again i am not trying to solve a problem/erro but i still am very curious about why we can't use await alone without async.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • The async keyword creates a special function that runs outside the main thread and can pause and resume. Using await requires such a function. The latest node versions allow using await at the top level, since blocking the main thread is not as bad as inside a browser environment. –  Sep 17 '20 at 11:58
  • @Chris `async` functions do *not* "run outside the main thread". They still run on the same thread as anything else. The async call they `await` might then be running on a different, lower-level background thread. – deceze Sep 17 '20 at 11:59
  • Purely syntactically, `await` _could_ be made to work without `async`. But logically, an `await`ed value will only be available *sometime later*, and that "infects" everything up the call chain (i.e. the caller will have to `await`, and *its* caller will have to, and so on). So, it does make sense to mark those functions specifically, even beyond other implementation detail advantages that might bring. – deceze Sep 17 '20 at 12:02
  • @deceze thanks, I didn't know that. Now I do, which is great! –  Sep 17 '20 at 12:02
  • Specifically for your example: Because then `result` would not be available immediately on the next line. – deceze Sep 17 '20 at 12:12

1 Answers1

2

Why does "await" always need an "async" ?

This is because if you were able to put await in synchronous code, you would block the (main) thread.

This was already possible to do before async and await keywords.

You can simply resolve a promise. An async function returns such a promise.

Webber
  • 4,672
  • 4
  • 29
  • 38
  • It doesn't really answer why the async can't then be implicitly inferred from using await, no? – Flater Sep 17 '20 at 11:58
  • 1
    I mean technically it's possible to add that to the javascript specification. There's a reason why they didn't. – Webber Sep 17 '20 at 12:00