写在前面
本来是一篇关于JS中循环发起Axios请求的Bug记录,以为是循环使用错误导致异步/同步操作出问题不能向后台拿数据,结果这篇文章快写完的时候才发现是原来我自己写错变量名了。。
项目场景
基于Vue+Spring Boot+MyBatis框架的菜品管理系统,消费者在前端修改购物车中菜品的数量,实时修改后台数据库数据。
问题描述
SpringBoot后端收不到前端发来的数据库操作请求。
解决方案
其实forEach也能用,变量名别写错就好了(扶额(具体到底能不能用/怎么用/什么时候能用我也不是很清楚,我没系统学过JS,至少目前在我的项目里是能这么用的
// 计算总额
handleSum() {
this.sum = 0
this.tableData.forEach(item => {
this.sum += (item.price * item.num)
this.$axios.post('/carts/updateNum', {
consumerid: this.consumerid,
name: item.name,
size: item.size,
num: item.num
}).then(resp => {
if (resp && resp.status === 200) {
this.loadDishes()
}
}).catch(() => {
console.log('error')
})
})
}
运行结果(以修改米饭的数量由2至1为例):
如果forEach不能用的话,试试换别的循环:
forEach 只支持同步代码。forEach 只是简单的执行了下回调函数而已,并不会去处理异步的情况。并且你在 callback 中即使使用 break 也并不能结束遍历。在循环中使用async await,要使用for…of 或者 for 循环, while循环。
参考:for循环中的函数使用axios请求数据,拿不到数据?
// 计算总额
handleSum() {
this.sum = 0
for (let i = 0; i < this.tableData.length; i++) {
this.sum += this.tableData[i].price * this.tableData[i].num
this.$axios.post('/carts/updateNum', {
consumerid: this.consumerid,
name: this.tableData[i].name,
size: this.tableData[i].size,
num: this.tableData[i].num
}).then(resp => {
if (resp && resp.status === 200) {
this.loadDishes()
}
}).catch(() => {
console.log('error')
})
}
}