-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathcallback_hell.js
More file actions
61 lines (58 loc) · 1.6 KB
/
callback_hell.js
File metadata and controls
61 lines (58 loc) · 1.6 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
let random_pokemon = []
let image_array = []
$.get('http://pokeapi.co/api/v2/pokemon'
).then(
function(data) {
let count = data.count
console.log("Retrieved count")
return $.get('http://pokeapi.co/api/v2/pokemon/?limit=' + count)
}
).then(
function(data) {
console.log("Retrieved all pokemon")
let all_pokemon = data.results
random_pokemon = pick_three_randomly(all_pokemon)
return $.get(random_pokemon[0].url)
}
).then (
function(pokemon_data) {
console.log("Retrieved first pokemon")
add_image_to_array(image_array, pokemon_data)
return $.get(random_pokemon[1].url)
}
).then (
function(pokemon_data) {
console.log("Retrieved second pokemon")
add_image_to_array(image_array, pokemon_data)
return $.get(random_pokemon[2].url)
}
).then (
function(pokemon_data) {
console.log("Retrieved third pokemon")
add_image_to_array(image_array, pokemon_data)
$("body").empty()
for (let i = 0; i < image_array.length; ++i) {
let img = image_array[i]
$("body").append(
$("<h1>", {text: img.name}),
$("<img>", {src: img.front}),
$("<img>", {src: img.back})
)
}
})
function add_image_to_array(image_array, pokemon_data) {
image_array.push({
name: pokemon_data.name,
front: pokemon_data.sprites.front_default,
back: pokemon_data.sprites.back_default
})
}
function pick_three_randomly(data_array) {
let chosen = []
let count = data_array.length
for (let i = 0; i < 3; ++i) {
let random_index = Math.floor(Math.random() * count)
chosen.push( data_array[random_index] )
}
return chosen
}