最近遇到一个场景,需要我读取一个数组的内容,然后写个for循环来发送请求,在请求发送结束后调用一个函数,代码如下
getFoodList: function () {
var that = this;
for (var i = 0; i < that.data.recordDate.length; i++) {
var date = that.data.recordDate[i].date;
wx.request({
url: getApp().globalData.url
data: {
secretKey: that.data.secretKey,
eatDate: date
},
header: {
'content-type': 'application/json'
},
success: function (res) {
if (res.data.foodLists != undefined)
that.data.foodInfo.push(res.data.foodLists);
that.setData(
{
foodInfo: that.data.foodInfo
}
)
}
})
}
that.setShowFlag();
},
因为微信小程序异步加载的特性,这样写显然无法满足我执行完请求后调用方法的需求。
对此,最优秀的解决方案应该是用promise,网上有许多博客,但我一时半会没能用起来,这边给大家推荐一个蠢办法,解决燃眉之急。就是使用setInterval让他等待请求执行,等请求执行完毕了再调用你希望调用的方法。
代码如下:
var timer = setInterval(function () {
console.log("循环定时器等待循环请求结束")
console.log("that.data.recordDate.length:" + that.data.recordDate.length)
console.log("that.data.foodInfo.length:" + that.data.foodInfo.length)
if (that.data.recordDate.length == that.data.foodInfo.length)
{
that.setShowFlag();
clearInterval(timer);
}
}
, 500)