Loading lessons...
Async and Await
Async and Await
async and await make promises much easier to write and read.
The async keyword
async marks a function as asynchronous. It always returns a promise:
async function getData() {
return "data";
}
getData(); // a Promise
The await keyword
await pauses an async function until a promise settles, then gives you the result:
async function showUser() {
const user = await fetchUser();
console.log(user);
}
Await only works inside async
You can only use await inside an async function.
Error handling with try/catch
async function getData() {
try {
const data = await fetchSomething();
console.log(data);
} catch (err) {
console.log("Failed: " + err.message);
}
}
Why async/await?
- Reads like normal synchronous code.
- No more chaining .then and .catch everywhere.
- Errors handled with familiar try/catch.
TL;DR
- async functions return promises.
- await pauses until a promise settles.
- await only works inside async functions.
- Use try/catch for errors.