Node.js Course
Node.js
/
Beginner

Async / Await

Definition

Syntactic sugar built on top of Promises that allows asynchronous code to be written in a top-to-bottom, synchronous-looking style.

Explain Like I'm New

Promises fixed the callback pyramid, but `.then().then()` still looked a bit messy. `async/await` lets you tell JavaScript: 'Pause the function on this line. Wait for the database to finish. Once it finishes, put the result in this variable and proceed to the next line.' It makes async code read exactly like normal sync code.

Real World Example

Writing an Express route: `const user = await User.findById(req.params.id); res.send(user);`

Common Use Cases

  • •Clean, readable asynchronous logic
  • •Easy try/catch error handling

Interactive Example

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

Interview Questions

basic

  • What happens if you use `await` inside a function that doesn't have the `async` keyword?

intermediate

  • What does an `async` function always return, even if you just `return 5`?

advanced

  • Does `await` actually pause the entire Node.js server thread?

Flash Cards

Question

What does an async function return?

Click to reveal answer
Answer

It ALWAYS returns a Promise. If you write `async function getNum() { return 5; }`, calling `getNum()` returns a Promise that resolves to 5. You must `.then()` or `await` it.

Question

Does await pause the Node server?

Click to reveal answer
Answer

NO! This is a crucial concept. `await` ONLY pauses the specific function it is inside. The rest of the Node.js server (the Event Loop) keeps spinning, happily serving thousands of other users while that one function waits.