Add lesson 8: async/await without tears
3 changed files with 40 additions and 0 deletions
lessons/08-async-await-without-tears/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 8: async/await without tears | |
| 2 | + | |
| 3 | +We look at async/await without tears the way working developers use it, with examples you can change and run right away. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/javascript-web/lessons/8](https://glibcode.net/courses/javascript-web/lessons/8) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `async.js`: the same request with async/await | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +node async.js | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/08-async-await-without-tears/async.js ADDED
| @@ -0,0 +1,16 @@ | ||
| 1 | +async function forecast(city) { | |
| 2 | + const res = await fetch(`/api/weather?city=${encodeURIComponent(city)}`); | |
| 3 | + if (!res.ok) throw new Error(`HTTP ${res.status}`); | |
| 4 | + return res.json(); | |
| 5 | +} | |
| 6 | + | |
| 7 | +async function main() { | |
| 8 | + try { | |
| 9 | + const f = await forecast("Lisbon"); | |
| 10 | + console.log(f.temperature); | |
| 11 | + } catch (err) { | |
| 12 | + console.error(err.message); | |
| 13 | + } | |
| 14 | +} | |
| 15 | + | |
| 16 | +main(); | |
lessons/08-async-await-without-tears/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 8 | |
| 2 | + | |
| 3 | +1. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to? | |
| 4 | +2. Run `async.js` and change one value. Write down what you expect, then run it again and compare. | |
| 5 | +3. Add a comment above each block explaining what it does, in your own words. | |