为什么要为循环和一个循环循环返回我最后一次迭代的信息?
在这里,我正在玩硬币壁虎API。我试图将比特币的价格记录下来,而10不等于0,因此基本上是10次。它可以正常工作,只有迭代不会相应显示。相反,它只是显示最后一次迭代,而不是每次实际迭代。
**似乎迭代在Axios调用中没有相应地记录,但是当我在其上方的console.log(迭代)时,它可以正常工作。
const [coinData, setCoinData] = useState([])
iteration = 10
while (iteration != 1) {
axios.get(`https://api.coingecko.com/api/v3/coins/bitcoin/history?date=11-04-2022`).then((res) => {
console.log(iteration, res.data.market_data.current_price.usd)
setCoinData(iteration, res.data.market_data.current_price.usd)
}).catch((err) => {
console.log(err)
})
iteration--
}
控制台日志返回此9:1 42274.907370256085
instead of:
9 42274.907370256085
8 42274.907370256085
7 42274.907370256085
etc:
Here I am playing around with the coin gecko api. I am trying to log the price of bitcoin while 10 is not equal to 0, so basically 10 times. It works fine, only the iteration doesn't show accordingly. Instead it just shows the last iteration instead of every time it actually iterates.
**seems as though iteration doesn't log accordingly inside the axios call but when I do console.log(iteration) just above it, It works fine.
const [coinData, setCoinData] = useState([])
iteration = 10
while (iteration != 1) {
axios.get(`https://api.coingecko.com/api/v3/coins/bitcoin/history?date=11-04-2022`).then((res) => {
console.log(iteration, res.data.market_data.current_price.usd)
setCoinData(iteration, res.data.market_data.current_price.usd)
}).catch((err) => {
console.log(err)
})
iteration--
}
the console log returns this 9 : 1 42274.907370256085
instead of:
9 42274.907370256085
8 42274.907370256085
7 42274.907370256085
etc:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 Robby Cornelissen 所说,.then().catch() 是异步的。
异步行为基本上就像您运行某些代码时一样,但不要等到它完成后再运行其下面的代码。
您可以在这里阅读更多相关信息: https://www.w3schools.com/js/js_async .asp
一种解决方案是使用 try/catch wait。
请记住,我正在尝试通过移动设备提供帮助,因此我无法对此进行测试,并且代码格式可能有点奇怪。
As Robby Cornelissen stated, .then().catch() is asynchronous.
Asynchronous behaviour is basically like when you run some code, but don't wait for it to finish before you run the code below it.
You can read more up about it here: https://www.w3schools.com/js/js_async.asp
One solution would be to use try/catch await.
Keep in mind that I am trying to help from a mobile device, so I am unable to test this and the code formatting might be a bit wonk.