What are async and await in JS?
async
: Declares a function as asynchronous. It always returns a Promise.
await
: Pauses the execution of an async function until the Promise is resolved or rejected.
Why do we use async
and await
?
- To make asynchronous code look and behave more like synchronous code.
- It improves readability and avoids callback hell or complex
.then()
chains.
Can you use await
outside of an async
function?
- No,
await
can only be used inside an async function. Using it outside will result in a syntax error