JavaScript Course
JavaScript
/
Intermediate

Async / Await

Definition

async and await are extensions of Promises. They act as syntactic sugar on top of Promises, allowing you to write asynchronous, promise-based behavior in a cleaner style that looks like synchronous code.

Explain Like I'm New

Using Promises with '.then()' can get messy, like a long chain of instructions. 'async/await' lets you write code top-to-bottom, pausing execution on the 'await' line until the task is done, making it read like a simple recipe.

Real World Example

When fetching a user's profile, and then fetching their posts based on their ID. With async/await, you just 'await' the profile, then on the very next line, 'await' the posts, rather than nesting callbacks.

Common Use Cases

  • •Simplifying complex Promise chains
  • •Making asynchronous code easier to read and maintain
  • •Handling asynchronous errors cleanly using standard try/catch blocks

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What does the 'async' keyword do to a function?
  • Where can you use the 'await' keyword?

intermediate

  • How do you handle errors with async/await?
  • Can you use await inside a regular for-loop? What happens?

advanced

  • How can you await multiple promises concurrently instead of sequentially?
  • What is top-level await?

trick

  • If you don't put 'await' in front of a function that returns a Promise, what does the variable contain?

Flash Cards

Question

What does the 'async' keyword do to a function?

Click to reveal answer
Answer

It ensures that the function always returns a Promise. Even if you just return a regular value like '5', it will automatically wrap it in a resolved Promise.

Question

How do you handle errors with async/await?

Click to reveal answer
Answer

You wrap your awaited calls inside a standard try...catch block, just like you would for synchronous errors.

Question

How can you await multiple promises concurrently?

Click to reveal answer
Answer

If they don't depend on each other, you shouldn't await them one by one. Instead, create all the promises, put them in an array, and use 'await Promise.all([p1, p2])'.