for循环里执行异步操作

在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”

解决方法(代码):

  1. 递归
  • 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) //获取图片信息
        }
      })
    }
  },
  1. 使用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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容