代码是这样的:
getCloudCapacity () {
let cloudIdList = this.cloudIdList
for (let i = 0; i < cloudIdList.length; i++) {
this.$http({
url: this.$http.adornUrl('/cloud/getCloudCapacity'),
method: 'get',
params: this.$http.adornParams({
cloudId: cloudIdList[i]
})
}).then(({ data }) => {
if (data && data.code === 0) {
JSON.parse(JSON.stringify(data.data))
this.cloudCapacityList.push(data.data)
} else {
this.$message({
type: 'error',
message: `获取${cloudIdList[i]}容量失败`
})
}
})
}
console.log('22222222', this.cloudCapacityList, '数据长度:', this.cloudCapacityList.length)
}
解决后:
加了两个关键字 async/await
原因:js是同步执行,本项目中for循环中调用接口,是异步代码,console.log会在循环结束之前就执行,这样console.log的变量还是未改变的状态。
使用asnyc和await使for循环结束后再执行后面的代码。
一些关于asnyc和await的文章:
https://www.cnblogs.com/SamWeb/p/8417940.html