Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Async/await is syntactic sugar over promises that makes async code look and behave like synchronous code. No more .then() chains - write cleaner, more readable code!
Put async before a function to make it always return a promise
// Regular function
function regularFunction() {
return 'Hello';
}
// Async function - automatically returns a promise
async function asyncFunction() {
return 'Hello';
}
// Both are promises!
asyncFunction().then(result => {
console.log(result); // 'Hello'
});Always return promises
Use await before a promise to pause and wait for the result
await inside async functions!async function fetchData() {
const response = await fetch('/api/data');
const data = await response.json();
console.log(data);
}
// Without await (promises):
function fetchData() {
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data));
}Pausing for promises
Wrap await in try/catch to handle errors
async function fetchUser() {
try {
const response = await fetch('/api/user');
if (!response.ok) {
throw new Error('Failed to fetch');
}
const user = await response.json();
console.log('Success:', user);
return user;
} catch (error) {
console.log('Error:', error.message);
return null;
}
}
fetchUser();try/catch with async/await
async function loadData() {
const user = await fetchUser();
const posts = await fetchPosts();
const stats = await fetchStats();
// Takes 6 seconds total
// (2s + 2s + 2s)
}async function loadData() {
const [user, posts, stats] =
await Promise.all([
fetchUser(),
fetchPosts(),
fetchStats()
]);
// Takes 2 seconds total!
}Run independent operations together