UNPKG

1.11 kBJavaScriptView Raw
1const { buffer, flatten, pipeline, transform } = require('streaming-iterables')
2const got = require('got@11.8.1')
3
4// A generator to fetch all the pokemon from the pokemon api
5const pokedex = async function* () {
6 let offset = 0
7 while(true) {
8 const url = `https://pokeapi.co/api/v2/pokemon/?offset=${offset}`
9 const { results: pokemon } = await got(url).json()
10 if (pokemon.length === 0) {
11 return
12 }
13 offset += pokemon.length
14 yield pokemon
15 }
16}
17
18// lets buffer two pages so they're ready when we want them
19const bufferTwo = buffer(2)
20
21// a transform iterator that will load the monsters two at a time and yield them as soon as they're ready
22const pokeLoader = transform(2, async ({ url }) => got(url).json())
23
24// string together all our functions with a flatten to get one pokemon at a time
25const pokePipe = pipeline(pokedex, bufferTwo, flatten, pokeLoader)
26
27// lets do it team!
28const run = async () => {
29 for await (const pokemon of pokePipe){
30 console.log(pokemon.name)
31 console.log(pokemon.sprites.front_default)
32 }
33}
34
35run().then(() => console.log('caught them all!'))