mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-10-24 23:49:06 +08:00
feat(curriculum): add interactive examples to async/await lesson (#64145)
This commit is contained in:
+5
-1
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user