> Why can't non-async functions use await()?
To await means to wait for a Promise to resolve asynchronously. That's why async functions return a Promise instance.
async function asyncFn() {
const result = await fetch(url)
const json = await result.json()
return json
}
asyncFn().then(json => console.log('Got', json))
console.log('Fetching result..')
Calling asyncFn() will immediately return a Promise instance. Then each await in the function waits for a Promise to resolve, before continuing to the next instruction. While that's happening, other code can keep running, like the last line in the example above.In contrast, a non-async function is synchronous, which means it's expected to run all instructions one after the other, then return a value. No other code can run while that's happening.
If await was allowed in a non-async function, it would have to block execution of all other code until the Promise is resolved/rejected.
function syncFn() {
const result = await fetch(url) // Stop the world
const json = await result.json() // Stop the world
return json
}
console.log('Fetching result..')
console.log('Got', syncFn())
This is how a synchronous HTTP request works: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequ...To avoid stopping the world, a non-async function can use Promise callbacks instead.
function promiseFn() {
return fetch(url)
.then(result => result.json())
}
promiseFn().then(json => console.log('Got', json))
console.log('Fetching result..')