情景是这样的,h5商城通过接口1获取到楼层,比如有4个,然后循环4个楼层,在循环里面获取里面的产品,然后把楼层以及下面产品重组后push到当前页面data里面,页面循环然后就能显示出来楼层以及产品了。但是结果发现返回的楼层结果是乱的,循环发送了4个异步请求,4个请求的返回结果顺序每次可能会不一样导致的顺序错乱。
const louceng_arr = []
result.data[0].dss_list.forEach(item => {
const shop_special_id = item.shop_special_id
//调用接口获取产品
Api.getSpecialGoodslist({
specialId: shop_special_id,
token: uni.getStorageSync('token'),
is_token: 0
})
.then(result1 => {
const goodlist_arr = new Array()
result1.rows.forEach(item1 => {
goodlist_arr.push({
goods_id: item1.goods_id,
goods_name: item1.goods_name,
goods_image: item1.pc_img,
goods_price_min: item1.member_integral
})
})
app.items.push({
name: item.special_name,
type: "goods",
params: {
"source": "auto",
"banner":item.special_img,
"auto": {
"category": 0,
"goodsSort": "all",
"showNum": 6
}
},
style: {
"background": "#F6F6F6",
"display": "list",
"column": 2,
"show": ["goodsName", "goodsPrice", "linePrice",
"sellingPoint", "goodsSales"
]
},
data: goodlist_arr
})
})
})
在uni-app框架里,遇到这样的类似代码时,可以用递归算法来避免for循环结束了,异步请求还没有结束的问题,将上面的代码修改成递归形式,如下:
//把楼层赋值给一个简短的数组
const louceng_arr = result.data[0].dss_list
var i = 0;
getLouceng();
function getLouceng() {
if (i >= louceng_arr.length) {
return;
}
const shop_special_id = louceng_arr[i].shop_special_id
//调用接口获取产品
Api.getSpecialGoodslist({
specialId: shop_special_id,
token: uni.getStorageSync('token'),
is_token: 0
})
.then(result1 => {
const goodlist_arr = new Array()
result1.rows.forEach(item1 => {
goodlist_arr.push({
goods_id: item1.goods_id,
goods_name: item1.goods_name,
goods_image: item1.pc_img,
goods_price_min: item1.member_integral
})
})
app.items.push({
name: louceng_arr[i].special_name,
type: "goods",
params: {
"source": "auto",
"banner": louceng_arr[i].special_img,
"auto": {
"category": 0,
"goodsSort": "all",
"showNum": 6
}
},
style: {
"background": "#F6F6F6",
"display": "list",
"column": 2,
"show": ["goodsName", "goodsPrice", "linePrice",
"sellingPoint", "goodsSales"
]
},
data: goodlist_arr
})
i++
getLouceng();
})
}
问题得以解决!!!