【发布时间】:2021-03-02 06:52:20
【问题描述】:
我这里有一段代码。它获取 4 个对 pokiapi 的 API 调用,将响应转换为 JSON,然后将该响应转换为仅显示名称,因此当 Promise.all() 解析时,它应该返回一个包含 4 个口袋妖怪名称的数组。
handleClick(event) {
event.preventDefault()
const randNum1 = Math.floor(Math.random() * this.totalPokemon)
const randNum2 = Math.floor(Math.random() * this.totalPokemon)
const randNum3 = Math.floor(Math.random() * this.totalPokemon)
const randNum4 = Math.floor(Math.random() * this.totalPokemon)
Promise.all([
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum1),
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum2),
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum3),
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum4),
])
.then(responses => Promise.all(responses.map(r => r.json())))
.then(responses => Promise.all(responses.map(r => r.name)))
.then(responses => console.log(responses))
}
最后一行代码是控制台记录响应,我得到了我所期望的,这是一个口袋妖怪名称数组。一个例子可能是 ["mewtwo", "jynx", "ponyta", "geodude"]。
但是,当我在控制台日志之前添加一个新行以使用fisherYatesShuffle() 对前一个数组进行洗牌时,控制台日志现在返回未定义:
handleClick(event) {
event.preventDefault()
const randNum1 = Math.floor(Math.random() * this.totalPokemon)
const randNum2 = Math.floor(Math.random() * this.totalPokemon)
const randNum3 = Math.floor(Math.random() * this.totalPokemon)
const randNum4 = Math.floor(Math.random() * this.totalPokemon)
Promise.all([
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum1),
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum2),
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum3),
fetch('https://pokeapi.co/api/v2/pokemon/' + randNum4),
])
.then(responses => Promise.all(responses.map(r => r.json())))
.then(responses => Promise.all(responses.map(r => r.name)))
.then(responses => this.fisherYatesShuffle(responses))
.then(responses => console.log(responses))
}
我不认为fisherYatesShuffle() 方法是错误的,因为我已经在我为测试目的而制作的其他阵列上尝试过它,并且非常好。以防万一,这里是fisherYatesShuffle()的实现。
//Takes in an array and returns a shuffled array
fisherYatesShuffle(guesses) {
for (let i = guesses.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * i)
const temp = guesses[i]
guesses[i] = guesses[j]
guesses[j] = temp
}
}
我怀疑这是响应返回方式的问题,但会是什么?
编辑:啊显然问题是我的fisherYatesShuffle() 方法。我最初用我制作的一些随机数组对其进行了测试,但我的测试一定很糟糕,因为它没有发现我的错误。
【问题讨论】:
标签: javascript arrays promise response shuffle