feat(curriculum): add interactive examples to async/await lesson (#64145)

This commit is contained in:
Diem-Trang Pham
2025-11-25 10:33:36 -08:00
committed by GitHub
parent 4f82fafbef
commit 583555e9b7
@@ -5,12 +5,14 @@ challengeType: 19
dashedName: what-is-async-await-and-how-does-it-work
---
# --description--
# --interactive--
In the previous lessons, you learned about asynchronous programming which allows other code to run while we wait for some time-consuming tasks to complete, like fetching data from a server, reading data from a file, and so on.
`async`/`await`, built on top of promises, makes writing and reading asynchronous code easier. When you put the `async` keyword before a function, it means that function will always return a `Promise`. Only inside an `async` function, you can use the `await` keyword, which allows you to wait for a `Promise` to resolve before moving on to the next line of code. Here's an example to illustrate how `async`/`await` works:
:::interactive_editor
```js
async function delayedGreeting(name) {
console.log("A Messenger entered the chat...");
@@ -22,6 +24,8 @@ delayedGreeting("Alice");
console.log("First Printed Message!");
```
:::
In this code, we define an `async` function called `delayedGreeting`. Inside this function, we use `await` to pause the execution for 2 seconds. After the delay, it prints a greeting.
When we call this function, you'll see `First Printed Message!` appear before the greeting. This is because the function is asynchronous - it doesn't block the rest of the code from running.