-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconditionals.ts
More file actions
40 lines (31 loc) · 924 Bytes
/
Copy pathconditionals.ts
File metadata and controls
40 lines (31 loc) · 924 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import fetch from 'node-fetch';
interface PokemonResults {
count: number
next?: string
previous?: string
results: {
name: string
url: string
}[]
}
type fetchPokemonResult<T> = T extends undefined
? Promise<PokemonResults>
: void
function fetchPokemon<T extends undefined | ((data: PokemonResults) => void)>(url: string, cb?: T)
: fetchPokemonResult<T> {
if (cb) {
fetch(url)
.then(res => res.json())
.then(cb)
return undefined as fetchPokemonResult<T>
} else {
return fetch(url).then(res => res.json()) as fetchPokemonResult<T>
}
}
// fetchPokemon('https://pokeapi.co/api/v2/pokemon?limit=10', (data) => {
// data.results.forEach(pokemon => console.log(pokemon.name))
// })
(async function () {
const data = <PokemonResults>(await fetchPokemon('https://pokeapi.co/api/v2/pokemon?limit=10'))
data.results.forEach(pokemon => console.log(pokemon.name))
})()