JavaScript Async & Await
JS
What are async
& await
?
async
and await
are special keywords in JavaScript that make working with Promises easier and your asynchronous code look more like synchronous code.
They are essentially syntactic sugar over Promises, introduced in ES2017.
async
function
If you put async before a function, it always returns a Promise, even if you return a normal value.
Await
Function
You can only use await inside an async function.
It pauses the function execution until the Promise is resolved, then returns the resolved value.
Example: Fetch API with await
await fetch(...)
waits for the HTTP response.await response.json()
waits for JSON parsing.try...catch
handles errors, like if network fails.
Why is async/await better?
- Avoids callback hell.
- Avoids chaining .then().
- Looks like normal step-by-step code.