javascript · level 3 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
loops over values that arrive over time.
Servers rarely send everything at once. A long list comes back in pages, called : ask for page 1, then page 2, until a page says there are no more. Writing that loop by hand, everywhere you need the list, gets messy.
An wraps it up: async function* can await a request, then yield each item. Whoever uses it writes for await...of, which waits for each value in turn. The paging logic stays hidden in one place.
async function* allProducts() {
let page = 1;
while (page !== null) {
const reply = await fetch(`https://api.example.com/products?page=${page}`);
const data = await reply.json();
for (const item of data.items) { yield item; }
page = data.next;
}
}
for await (const product of allProducts()) {
console.log(product);
} Gwecode's practice server answers these page requests, and each page says which page comes next.
guess first
Stop after a short page. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
async function* pages() {
for (let page = 1; page <= 3; page++) {
console.log(`fetching page ${page}`);
const reply = await fetch(`https://api.example.com/feed?page=${page}`);
yield await reply.json();
}
}
for await (const posts of pages()) {
console.log(`got ${posts.length}`);
if (posts.length < 2) { break; }
}
your turn
Your turn. Add up the takings.
Fill in the word that makes the loop wait for each order, and the property that holds each order's price in pence.
fix it
The sensors will not start. Can you fix it?
- The SyntaxError comes from
awaiton line 3. Which kind of function may useawait? - Only async functions can
await. This generator is missing a word at the start. - Write
asyncbeforefunction*on line 1, then press run.
nailed it
you can stream data page by page. :D
async function*can await requests and yield each item.for await...ofwaits for every value in turn.- Hide pagination inside a generator so callers stay simple.
new words in your collection
- pagination
- async generator
- for await...of
This lesson isn’t saved. A free account remembers every lesson you finish.