UNPKG

1.13 kBJavaScriptView Raw
1const { buffer, flatten, pipeline, transform } = require('streaming-iterables')
2const got = require('got')
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 { body: { results: pokemon } } = await got(url, { json: true })
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 }) => {
23 const { body } = await got(url, { json: true })
24 return body
25})
26
27// string together all our functions
28const pokePipe = pipeline(pokedex, bufferTwo, flatten, pokeLoader)
29
30// lets do it team!
31const run = async () => {
32 for await (const pokemon of pokePipe){
33 console.log(pokemon.name)
34 console.log(pokemon.sprites.front_default)
35 }
36}
37
38run().then(() => console.log('caught them all!'))