JS Learning

Asynchronous Programming

Lesson Progress0%

Async/Await

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Async/await is the modern way to work with asynchronous code. It makes async code look and feel like normal, synchronous code - much easier to read and write!

The Magic Words:

  • async - Marks a function as asynchronous
  • await - Pauses and waits for a Promise to complete

Basic syntax:

async function myAsyncFunction() {
const result = await someAsyncOperation();
console.log(result);
}

Converting Promise chains to async/await:

// Old way with Promises:
fetchUser()
.then(user => fetchPosts(user.id))
.then(posts => console.log(posts))
.catch(error => console.error(error));
// New way with async/await:
async function getUserPosts() {
try {
const user = await fetchUser();
const posts = await fetchPosts(user.id);
console.log(posts);
} catch (error) {
console.error(error);
}
}

Error handling with try/catch:

async function getData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to fetch data:', error);
}
}

Key benefits:

  • Reads like normal, sequential code
  • Easier error handling with try/catch
  • Simpler debugging
  • Works great with loops

Remember: async functions always return a Promise!

Ready to practice? Try the exercise below to reinforce your learning!

Try it yourself

Create an async function that waits for multiple operations using await.

Loading...