Async/Await

Modern Async

Lesson 86
+30 XP
Step 1 of 5

Async/Await: Modern JavaScript

Async/Await is a modern way to work with promises that makes async code look and behave like synchronous code.

Key Concept: Instead of chaining .then(), you can write async code that reads like normal, top-to-bottom code!

Before (Promises):

fetchUser(1)
  .then(user => {
    console.log(user);
    return fetchPosts(user.id);
  })
  .then(posts => {
    console.log(posts);
  })
  .catch(error => {
    console.error(error);
  });

After (Async/Await):

async function getData() {
  try {
    let user = await fetchUser(1);
    console.log(user);

    let posts = await fetchPosts(user.id);
    console.log(posts);
  } catch (error) {
    console.error(error);
  }
}

getData();

Benefits of Async/Await:

  • Code reads top-to-bottom, easier to understand
  • No more nested .then() chains
  • Better error handling with try/catch
  • Works with all promises