Why "await" always need to be used in an "async" function

Viewed 353

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.

1 Answers

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.

Related