在for循环里执行异步操作,比如wx.getImageInfo()获取图片信息
举例:
var imgArray=["图片1","图片2","图片3"]
for(var i=0;i<imgArray.length;i++){
var index=i
wx.getImageInfo({
src: imgArray[index],
success (res) {
console.log("查询的图片:",imgArray[index])
}
})
}
理论上我们想得到的输出效果是:
查询的图片:图片1
查询的图片:图片2
查询的图片:图片3
但实际得到的输出效果是:
查询的图片:图片3
查询的图片:图片3
查询的图片:图片3
原因:
for循环时,对于这种异步操作,会先进行一次 “保存”,等到整个for循环执行结束后,再来执行
解析:
for循环执行结束时 i 的值为3(因为当 i=2 时,循环代码块执行完毕后,还是执行了i++,所以 i 的值为3),index的值为2(因为当 i=3 时,循环代码块并没有执行,所以 index 的值还是为2),因为wx.getImageInfo()是写在for循环中的,相当于存在3次调用,这3次调用均是在for循环结束后进行的,所以输出的都是 “图片3”
解决方法(代码):
- 递归
- index.wxml文件:
<button bindtap="q_xzImg">选择图片</button>
- index.js文件:
//选择图片
q_xzImg: function () {
var that = this
wx.chooseImage({
count: 9,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
console.log('选择的图片:', res.tempFiles)
that.q_imgInfo(0,res.tempFiles)//获取图片信息(起始坐标,图片数组)
}
})
},
//获取图片信息(起始坐标,图片数组)
q_imgInfo: function (index, array) {
var that = this
if (index < array.length) {
console.log("index is :", index)
console.log('array[index] is', array[index].path)
wx.getImageInfo({
src: array[index].path,
success: function (res) {
console.log('当前查询的图片:', array[index].path)
console.log('当前查询的图片信息:', res)
that.q_imgInfo(index + 1, array) //获取图片信息
}
})
}
},
- 使用async/await方法(async/await介绍)
- index.wxml文件:
<button bindtap="q_xzImg">选择图片</button>
- index.js文件:
//选择图片
q_xzImg: function () {
var that = this
wx.chooseImage({
count: 9,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
console.log('选择的图片:', res.tempFiles)
that.q_async(res.tempFiles) //使用async/await方法
}
})
},
//使用async/await方法
q_async: function (array) {
var that = this
var p = async function () {
try {
console.log('开始')
for (var i = 0; i < array.length; i++) {
await that.q_imgInfo2(array, i)//获取图片信息(图片数组,坐标)
}
console.log('结束')
} catch (err) {
console.log(err) //这里捕捉到错误error
}
}
p()
},
//获取图片信息(图片数组,坐标)
q_imgInfo2: function (array, index) {
var that = this
return new Promise(function (resolve, reject) {
wx.getImageInfo({
src: array[index].path,
success: function (res) {
console.log('当前查询的图片:', array[index].path)
console.log('当前查询的图片信息:', res)
resolve()
}
})
})
},
OK